在linux环境下写一个程序,实现从父进程发送一个字符到子进程的功能

来源:百度知道 编辑:UC知道 时间:2024/05/09 09:35:22
在linux环境下写一个程序,实现从父进程发送一个字符到子进程的功能

用管道连接

#include <stdio.h>
#include <unistd.h>

#define MAXSIZE 4096
int main ()
{
int n, fd[2];
pid_t pid;
char line[MAXSIZE];

if (pipe (fd) < 0){
printf ("pipe error!\n");
return (1);
}
if ((pid = fork()) < 0) {
printf ("fork error\n");
return (1);
}
else if (pid > 0) {
close (fd[0]);
write (fd[1], "hello, world\n", 12);
} else {
close (fd[1]);
n = read (fd[0], line, MAXSIZE);
write (STDOUT_FILENO, line, n);
}
return (0);
}