【问题标题】:writing to pipe signals synchronization写入管道信号同步
【发布时间】:2013-05-08 09:00:11
【问题描述】:

这是我想做的事情: (这是更大任务的一部分) 而且我一开始就卡住了。

我创建了分叉 p1、p2 进程并使用 execlp(单独的程序)的主进程。他们应该从 p1.txt(进程 p1)和 p2.txt(进程 p2)中每行读取一个单词并将其写入管道。然后在主进程中,proc_pr 被分叉(我没有它的源代码),当它希望从管道中读取一个单词然后将其写入第二个管道时,它应该向它们发送 SIGUSR 1。

我尝试在 p1 中编写简单的代码,但它在大多数情况下都不起作用,只是在某些情况下。我可以从 proc_pr 的输出中看出它向 p1 发送了信号,然后什么也没有发生。 我已经看到了使用 open()、read() 和 lseek() 的解决方案,但我使用了 fopen() 和 fgets()。 任何帮助表示赞赏。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>

#define MAXLENGTH 150               //definujme si maximalnu dlzku retazca

int fd; int data_processed;         //file deskriptor a premenna na pocitanie precitanych dat
char buff[150];                 //buffer
FILE *f;                    //smernik na prud suboru

/* odchytenie signalu, subor je uz otvoreny a fd nacitany */
void odchytenie(int sig)
{   
    /* read a line */
    if ( fgets ( buff, sizeof buff, f ) != NULL ) 
       {        
             /* write the line */
            fputs ( buff, stdout ); 

            /* store the word into pipe */
           write(fd,buff,strlen(buff));
       } 
       else 
        {
            //do something to stop the process and close the file
        }      

}

int main(int argc, char *args[])
{

 /* prevedieme retazec z parametra na cislo deskriptora pipe na zapis */
 fd = atoi(args[1]);

 /* otvorime subor p1 */
 f=fopen("p1.txt","r");

/* zabezpeci odchytenie signalu */
(void) signal(SIGUSR1,odchytenie);

/* pocka na signal, proces sa neukonci, ani sa nezavrie subor */
while(1) 
 {
    sleep(1);       
 } 

 /* close the file */ 
 fclose(f);

 /* exit with value 0 */
 exit(0);

}

【问题讨论】:

    标签: c linux signals pipe


    【解决方案1】:

    嗯,我想通了。问题出在主进程中。而且我可能应该在处理程序中使用异步安全函数。

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2018-09-25
      • 1970-01-01
      • 1970-01-01
      • 2013-05-30
      • 1970-01-01
      • 2011-04-25
      相关资源
      最近更新 更多