我需要使用SIGUSR1和SIGUSR2並從管道讀取一些文本。一個線程必須讀取奇數符號,而另一個線程必須讀取偶數符號。主線程打開.txt文件並將信息寫入管道,2個線程從管道讀取符號並寫入其.txt文件。 我試圖使用sigwait,但它看起來不能正常工作。有任何想法嗎? 非常感謝你)Linux C信號
#include <sys/types.h>
#include <unistd.h>
#include <iostream>
#include <printf.h>
#include <stdio.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <cerrno>
#include <signal.h>
#include <fcntl.h>
using namespace std;
static bool a=false;
static int c;
main(int argc, char** argv)
{
int fildes[2];
char ch,ch1,ch2;
FILE *fp,*f1,*f2;
int stat,sig;
sigset_t set1;
sigset_t set2;
sigemptyset(&set1);
sigemptyset(&set2);
sigaddset(&set1,SIGUSR1);
sigaddset(&set2,SIGUSR2);
sigprocmask(SIG_BLOCK,&set1,NULL);
sigprocmask(SIG_BLOCK,&set2,NULL);
pid_t p1,p2;
pipe(fildes);
cout<<argv[1]<< " " <<argv[2]<< " " <<argv[3]<<endl;
fp=fopen(argv[1],"r");
f1=fopen(argv[2],"a");
f2=fopen(argv[3],"a");
int chet=2;
p1=fork();
if (!p1)
{
do
{
sigwait(&set1,&sig);
read(fildes[0], &ch1, 1);
printf("%c",ch1);
fprintf(f1,"%c",ch1);
}
while(!a);
exit(0);
}
p2=fork();
if (!p2)
{
do
{
sigwait(&set2,&sig);
read(fildes[0], &ch2, 1);
printf("%c",ch2);
fprintf(f2,"%c",ch2);
}
while(!a);
exit(0);
}
else
{
while(!feof(fp))
{
ch=fgetc(fp);
write(fildes[1],&ch,1);
if(chet%2==0)
kill(p1,SIGUSR1);
else kill(p2,SIGUSR2);
chet++;
//sleep(1/10);
}
a=true;
wait(&stat);
close(fildes[0]);
close(fildes[1]);
fclose(f1);
fclose(f2);
fclose(fp);
}
}
Whay究竟發生了什麼?看起來它不能正常工作是不夠的信息 – user2717954 2014-11-22 16:16:14
你的代碼有一件事是錯誤的:它沒有任何錯誤處理。零。 – 2014-11-22 16:20:04
我給了他信貸,他從問題中刪除錯誤處理代碼,使其更易於讀取 – user2717954 2014-11-22 16:25:42