红联Linux门户
Linux帮助

这是有关linux中信号捕捉的题目,哪位高手能帮我做做吗,谢谢啦。

发布时间:2011-02-22 22:33:08来源:红联作者:hei鹰
这是书上的一道题目(根据下面这段话),把下面的两个程序合并成一个,要实现的功能为把管道的读端

注销,然后把SIFPIPE信号捕捉下来并通过 new_op()函数把这个信号的标号打印出来,请问这道题要怎

么做??我比较不懂的是要如何捕捉这个信号???

(向管道中写入数据时,linux将不保证写入的原子性,管道缓冲区一有空闲区域,写进程就会试图向管

道写入数据。如果读进程不读走管道缓冲区中的数据,那么写操作将一直阻塞。
注:只有在管道的读端存在时,向管道中写入数据才有意义。否则,向管道中写入数据的进程将收到内核

传来的SIFPIPE信号,应用程序可以处理该信号,也可以忽略(默认动作则是应用程序终止)。)



1:

#include
#include
#include
#include
#include

void new_op(int signum, siginfo_t *info, void *myact)
{
printf("receive signal %d\n", signum);
sleep(5);
}

int main(int argc,char**argv)
{
struct sigaction act;
int sig;
sig=atoi(argv[1]); //字符型转化成整形。

sigemptyset(&act.sa_mask);
act.sa_flags=SA_SIGINFO; // ???
act.sa_sigaction=new_op; //怎么突然间跑出个new_op ?? //是函数指针

if(sigaction(sig,&act,NULL) < 0)
{
printf("install sigal error\n");
}

while(1)
{
sleep(2);
printf("wait for the signal\n");
}
}




1:
#include
#include
#include
#include
#include
#include

int main(void)
{
int pipe_fd[2];
pid_t pid;
char r_buf[100];
char w_buf[4];
char* p_wbuf;
int r_num;
int cmd;
//void *memset(void *s, int c, size_t n);
memset(r_buf,0,sizeof(r_buf)); //给数组初始化为NULL;NULL的ASCII为0;
memset(w_buf,0,sizeof(r_buf));
p_wbuf=w_buf;

if(pipe(pipe_fd)<0)
{
printf("pipe create error\n");
return -1;
}

if((pid=fork())==0)
{
printf("child\n");

printf("\n");
close(pipe_fd[1]);//两个管道描述符好像关不关闭都一样;

sleep(2);//确保父进程关闭写端

r_num=read(pipe_fd[0],r_buf,100); //读端会等待写端;
printf("read num is %d the data read from the pipe is %d\n", r_num, atoi(r_buf));
//printf("read num is %d the data read from the pipe is %s\n", r_num, r_buf);

close(pipe_fd[0]);

printf("child exit\n");
}
else if(pid>0)
{
//sleep(10);
printf("parent\n");
close(pipe_fd[0]);//read
strcpy(w_buf,"111");
//sleep(5);
if(write(pipe_fd[1],w_buf,4)!=-1)
printf("parent write over\n");
sleep(8);
close(pipe_fd[1]);//write
printf("parent close fd[1] over\n");
printf("parent exit\n");
}

exit(0);
}
文章评论

共有 1 条评论

  1. miftoe 于 2011-02-23 08:42:15发表:

    帮楼主顶个