【发布时间】:2016-04-25 13:48:47
【问题描述】:
这是我之前问题的从头开始编写的。我真正需要实现的是:在未来 parent 工作能够关闭 pipe 的一端,以便 grandchild ( daemon ) 将收到 SIGPIPE。当我使用 1 解决方案时,它就像一个魅力(但这是在任何分叉之前)。当我使用 2 解决方案时,只有一次写入会生成 SIGPIPE。我该如何检查?通过发出: strace -f ./a.out 2>&1 | grep 管道
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
void child_become_daemon( int pfd[][2], int id )
{
int pid = fork();
if( pid == 0 )
{
dup2( pfd[id][1], 1 );
close( pfd[id][0] );
sleep( 5 ); //this is to be sure that opposite end is already closed
write( 1, "child", strlen( "child" ) );
}
if( pid > 0 )
{
exit( 0 );
}
}
int main()
{
int pid;
int numKids = 5;
int procNum;
int pfd[numKids][2];
for( int i = 0; i < numKids; ++i )
{
pipe( pfd[ i ] );
//close( pfd[i][0] );//1 all killed - perfect
}
for( procNum = 0; procNum < numKids; procNum++ ) {
pid = fork();
if( pid == 0 ) {
break;
}
}
if( pid == 0 ) {
printf( "I'm child %d\n", procNum );
child_become_daemon( pfd, procNum );
}
else {
for( int i = 0; i < numKids; ++i )
{
printf( "closing %d\n", i );
close( pfd[i][0] );//2 why only one will get killed
close( pfd[i][1] );
}
char buf[124] = { 0 };
for( int i = 0; i < numKids; ++i )
{
read( pfd[i][0], buf, 124 );
printf( "buf: %s\n", buf );
}
int p, status;
while ((p = wait(&status)) != -1)
fprintf(stderr, "p %d exits with %d\n", p, WEXITSTATUS(status));
}
return 0;
}
【问题讨论】:
标签: c linux operating-system embedded