Table of Contents
输入
输出
Explanation
解释
示例
Home Backend Development C++ C program example demonstrating fork() and pipe() functions

C program example demonstrating fork() and pipe() functions

Sep 20, 2023 pm 03:45 PM
c program fork() pipe()

C program example demonstrating fork() and pipe() functions

在本题中,我们将演示fork()和pipe()。在这里,我们将为 Linux 创建一个 C 程序,该程序将连接两个字符串,使用 2 个进程,其中一个进程将获取输入并将其发送给其他进程,其他进程将字符串与预定义的字符串连接起来并返回连接后的字符串。

第一让回顾一下fork()和pipe()

fork() - 它创建一个子进程,这个子进程有一个新的PID和PPID。

pipe()是一个Unix、Linux系统调用,用于进程间通信。

让我们举个例子来理解问题,

输入

Learn programming
Predefined string: at tutorialspoint
Copy after login

输出

Learn programming at tutorialspoint
Copy after login

Explanation

的中文翻译为:

解释

P1 take input of string “learn programming”
Copy after login

使用管道将其发送到 P2。

P2 连接字符串并将其发送回 p1,p1 将其打印出来。

在程序中,我们将创建两个进程,例如 P1和 P2 使用 fork() 函数。它有以下三个返回值,显示程序的状态。

返回值 < 0,进程创建失败。

返回值 = 0,子进程。

返回值 > 0,这将是子进程到父进程的进程 ID,即父进程将被执行。

我们将创建两个管道,一个用于从 P1 到 P2 进行通信,另一种是从 P2 到 P1,因为管道是一种方式。

演示 fork() 和 pipeline() 的 C 程序

示例

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<string.h>
#include<sys/wait.h>
int main(){
   int p12[2];
   int p21[2];
   char fixed_str[] = " at tutorialspoint";
   char input_str[100];
   pid_t P;
   if (pipe(p12)==-1 || pipe(p21)==-1 ){
      fprintf(stderr, "Filed to create pipe" );
      return 1;
   }
   scanf("%s", input_str);
   P = fork();
   if (P < 0){
      fprintf(stderr, "fork Failed" );
      return 1;
   }
   else if (P > 0){
      char concat_str[100];
      close(p12[0]);
      write(p12[1], input_str, strlen(input_str)+1);
      close(p12[1]);
      wait(NULL);
      close(p21[1]);
      read(p21[0], concat_str, 100);
      printf("Concatenated string %s</p><p>", concat_str);
      close(p21[0]);
   }
   else{
      close(p12[1]);
      char concat_str[100];
      read(p12[0], concat_str, 100);
      int k = strlen(concat_str);
      int i;
      for (i=0; i<strlen(fixed_str); i++)
      concat_str[k++] = fixed_str[i];
      concat_str[k] = &#39;\0&#39;;
      close(p12[0]);
      close(p21[0]);
      write(p21[1], concat_str, strlen(concat_str)+1);
      close(p21[1]);
      exit(0);
   }
}
Copy after login

输出

Concatenated string Learn at tutorialspoint
Copy after login

The above is the detailed content of C program example demonstrating fork() and pipe() functions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Translate the following into Chinese: C program to convert Roman numerals to decimal numbers Translate the following into Chinese: C program to convert Roman numerals to decimal numbers Sep 05, 2023 pm 09:53 PM

Given below is a C language algorithm to convert Roman numerals to decimal numbers: Algorithm Step 1 - Start Step 2 - Read Roman numerals at runtime Step 3 - Length: = strlen(roman) Step 4 - For i=0 to Length-1 Step 4.1-switch(roman[i]) Step 4.1.1-case'm': &nbs

C++ program to compare the lexicographic order of two strings C++ program to compare the lexicographic order of two strings Sep 04, 2023 pm 05:13 PM

Lexicographic string comparison means that strings are compared in dictionary order. For example, if there are two strings 'apple' and 'appeal', the first string will come last because the first three characters of 'app' are the same. Then for the first string the character is 'l' and in the second string the fourth character is 'e'. Since 'e' is shorter than 'l', it will come first if we sort lexicographically. Strings are compared lexicographically before being arranged. In this article, we will see different techniques for lexicographically comparing two strings using C++. Using the compare() function in C++ strings The C++string object has a compare()

C++ program to find the value of the inverse hyperbolic sine function taking a given value as argument C++ program to find the value of the inverse hyperbolic sine function taking a given value as argument Sep 17, 2023 am 10:49 AM

Hyperbolic functions are defined using hyperbolas instead of circles and are equivalent to ordinary trigonometric functions. It returns the ratio parameter in the hyperbolic sine function from the supplied angle in radians. But do the opposite, or in other words. If we want to calculate an angle from a hyperbolic sine, we need an inverse hyperbolic trigonometric operation like the hyperbolic inverse sine operation. This course will demonstrate how to use the hyperbolic inverse sine (asinh) function in C++ to calculate angles using the hyperbolic sine value in radians. The hyperbolic arcsine operation follows the following formula -$$\mathrm{sinh^{-1}x\:=\:In(x\:+\:\sqrt{x^2\:+\:1})}, Where\:In\:is\:natural logarithm\:(log_e\:k)

C program to find length of linked list C program to find length of linked list Sep 07, 2023 pm 07:33 PM

Linked lists use dynamic memory allocation, i.e. they grow and shrink accordingly. They are defined as collections of nodes. Here, a node has two parts, data and links. The representation of data, links and linked lists is as follows - Types of linked lists There are four types of linked lists, as follows: - Single linked list/Singly linked list Double/Doubly linked list Circular single linked list Circular double linked list We use the recursive method to find the length of the linked list The logic is -intlength(node *temp){ if(temp==NULL) returnl; else{&n

C++ program to print dictionary C++ program to print dictionary Sep 11, 2023 am 10:33 AM

A map is a special type of container in C++ in which each element is a pair of two values, namely a key value and a map value. The key value is used to index each item, and the mapped value is the value associated with the key. Regardless of whether the mapped value is unique, the key is always unique. To print map elements in C++ we have to use iterator. An element in a set of items is indicated by an iterator object. Iterators are primarily used with arrays and other types of containers (such as vectors), and they have a specific set of operations that can be used to identify specific elements within a specific range. Iterators can be incremented or decremented to reference different elements present in a range or container. The iterator points to the memory location of a specific element in the range. Printing a map in C++ using iterators First, let's look at how to define

C program uses rename() function to change file name C program uses rename() function to change file name Sep 21, 2023 pm 10:01 PM

The rename function changes a file or directory from its old name to its new name. This operation is similar to the move operation. So we can also use this rename function to move files. This function exists in the stdio.h library header file. The syntax of the rename function is as follows: intrename(constchar*oldname,constchar*newname); The function of the rename() function accepts two parameters. One is oldname and the other is newname. Both parameters are pointers to constant characters that define the old and new names of the file. Returns zero if the file was renamed successfully; otherwise, returns a nonzero integer. During a rename operation

C program to implement Euclidean algorithm C program to implement Euclidean algorithm Sep 17, 2023 pm 12:41 PM

The problem implements Euclidean's algorithm to find the greatest common divisor (GCD) and least common multiple (LCM) of two integers and outputs the results with a given integer. Solution The solution to implement Euclidean algorithm to find the greatest common divisor (GCD) and least common multiple (LCM) of two integers is as follows - the logic of finding GCD and LCM is as follows - if (firstno*secondno!=0){ gcd= gcd_rec(firstno,secondno); printf("TheGCDof%dand%dis%d",

Write a C program that uses the strncmp library function to compare two strings Write a C program that uses the strncmp library function to compare two strings Sep 09, 2023 pm 01:17 PM

Strncmp is a predefined library function, present in the string.h file, which is used to compare two strings and display which string is larger. strcmp function (string comparison) This function compares two strings. It returns the ASCII difference of the first non-matching character in the two strings. Syntax intstrcmp(string1,string2); If the difference is equal to zero, then string1=string2. If the difference is positive, string1>string2. If the difference is negative, string1<string2. Example strncmp function This function is used to compare the first n characters of two strings. syntax strn

See all articles