将值从子进程传递给父进程
先决条件:Pipe() 和 Fork() 基础
编写一个 C 程序,其中子进程接受一个输入数组并使用 pipe() 和 fork() 将其发送到父进程,然后在父进程中打印它。
例子:假设我们在子进程中有一个数组 a[]={1, 2, 3, 4, 5} ,那么输出应该是 1 2 3 4 5。
Input: 1 2 3 4 5
Output: 1 2 3 4 5
// C program for passing value from
// child process to parent process
#include
#include
#include
#include
#include
#include
#define MAX 10
int main()
{
int fd[2], i = 0;
pipe(fd);
pid_t pid = fork();
if(pid > 0) {
wait(NULL);
// closing the standard input
close(0);
// no need to use the write end of pipe here so close it
close(fd[1]);
// duplicating fd[0] with standard input 0
dup(fd[0]);
int arr[MAX];
// n stores the total bytes read successfully
int n = read(fd[0], arr, sizeof(arr));
for ( i = 0;i < n/4; i++)
// printing the array received from child process
printf("%d ", arr[i]);
}
else if( pid == 0 ) {
int arr[] = {1, 2, 3, 4, 5};
// no need to use the read end of pipe here so close it
close(fd[0]);
// closing the standard output
close(1);
// duplicating fd[0] with standard output 1
dup(fd[1]);
write(1, arr, sizeof(arr));
}
else {
perror("error\n"); //fork()
}
}
执行上述代码的步骤:
- 要编译,请编写gcc program_name.c
- 要运行,请编写./a.out