0
以下是我想要做的: (这是较大的作业的一部分) 而我被卡在了开始。写入管道信号同步
我已经创建了分叉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);
}