📄 pipe.c
字号:
/*
** use system call pipe() creat a pipe, parent process read two sentence from child process p1 and p2
*/
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
int main()
{
int status;
int fd[2];
char outpipe[100], inpipe[100];
pid_t pid1, pid2;
pipe( fd ); /* creat a pipe */
while( (pid1=fork()) == -1 ) /* loop until creat a child process */
;
if( pid1 == 0 ) /* child1 process */
{
lockf( fd[1], 1, 0 ); /* lock write port so that make sure write data to pipe safely */
sprintf( outpipe, "child 1 process is sending message!" );
write( fd[1], outpipe, 50 );
sleep(1);
lockf( fd[1], 0, 0 ); /* unlock write port */
exit(0);
}
else
{
while( (pid2=fork()) == -1 ) /* loop until creat a child process */
;
if( pid2 == 0 ) /* child2 process */
{
close(fd[0]); /* close read port to test if parent process can receive a SIGPIPE signal */
sleep(2);
lockf( fd[1], 1, 0 ); /* make child1 and child2 mutex */
sprintf( outpipe, "child 2 process is sending message!" );
write( fd[1], outpipe, 50 );
sleep(5);
lockf( fd[1], 0, 0 ); /* unlock write port */
printf( "over!" );
exit(0);
}
else
{
wait( 0 ); /* keep parent and child execute at the same time */
read( fd[0], inpipe, 50 );
printf( "%s\n", inpipe );
close( fd[0] ); /* close read port to test if parent process can receive a SIGPIPE signal */
wait(&status);
if( WIFSIGNALED(status) )
printf( "abnormal termination, signal number = %d\n", WTERMSIG(status) );
exit(0);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -