pipe(建立管道)
表头文件 #include<unistd.h>
定义函数 int pipe(int filedes[2]);
函数说明
pipe()会建立管道,并将文件描述词由参数 filedes 数组返回。
filedes[0]为管道里的读取端,所以pipe用read调用的
filedes[1]则为管道的写入端。
返回值: 若成功则返回零,否则返回-1,错误原因存于 errno 中。
错误代码:
EMFILE 进程已用完文件描述词最大量
ENFILE 系统已无文件描述词可用。
EFAULT 参数 filedes 数组地址不合法。
#include <unistd.h>
#include <stdio.h>
int main( void )
{
int filedes[2];
char buf[80];
pid_t pid;
pipe( filedes );
if ( (pid=fork()) > 0 )
{
printf( "This is in the father process,here write a string to the pipe.\n" );
char s[] = "Hello world , this is write by pipe.\n";
write( filedes[1], s, sizeof(s) );
close( filedes[0] );
close( filedes[1] );
}
else
{
printf( "This is in the child process,here read a string from the pipe.\n" );
read( filedes[0], buf, sizeof(buf) );
printf( "%s\n", buf );
close( filedes[0] );
close( filedes[1] );
}
waitpid( pid, NULL, 0 );
return 0;
}
[root@localhost src]# gcc pipe.c
[root@localhost src]# ./a.out
This is in the child process,here read a string from the pipe.
This is in the father process,here write a string to the pipe.
Hello world , this is write by pipe.
fork之后,操作系统会复制一个与父进程完全相同的子进程,虽说是父子关系,但是在操作系统 看来,他们更像兄弟关系,这2个进程共享代码空间,但是数据空间是互相独立的,子进程数据空间中的内容是父进程的完整拷贝,指令指针也完全相同,但只有一 点不同,如果fork成功,子进程中fork的返回值是0,父进程中fork的返回值是子进程的进程号,如果fork不成功,父进程会返回错误。
可以这样想象,2个进程一直同时运行,而且步调一致,在fork之后,他们分别作不同的工作,也就是分岔了。这也是fork为什么叫fork的原因。
至于那一个最先运行,可能与操作系统有关,而且这个问题在实际应用中并不重要,如果需要父子进程协同,可以通过原语的办法解决。
#include <unistd.h>;#include <sys/types.h>;main (){pid_t pid;pid=fork();if (pid < 0)printf("error in fork!");else if (pid == 0)printf("i am the child process, my process id is %d\n",getpid());elseprintf("i am the parent process, my process id is %d\n",getpid());}
结果是
[root@localhost c]# ./a.out
i am the child process, my process id is 4286
i am the parent process, my process id is 4285