我在主程序中從父進程創建兩個子進程。第一個和第二個孩子在創建後執行一個程序(signalSender)(與另一個孩子的pid一起作爲參數)。 signalSender具有信號處理程序,用於在進程之間發送信號。當第一個孩子執行signalShooter時,第二個孩子的pid作爲參數給出。當第二個孩子執行sigShooter時,第一個孩子的pid作爲參數給出。兩個子進程之間發送信號
1)我想通過信號處理程序在第二個孩子向第一個孩子發送信號後找到第一個孩子的孩子。我試圖將其保存到全局變量pid_t pid2,但它不起作用。
2)我也必須在這兩個孩子之間發送信號100次,但我不知道在哪裏使用「for循環」和「等待」信號。
The main program:
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
int main()
{
pid_t pid1,pid2,wid;
char *my_args[5];
int aInt = 368
char str[15];
pid1 = fork();
if (pid1 < 0)
{
fprintf(stderr, ": fork failed: %s\n", strerror(errno));
exit(1);
}
if(pid1 == 0)
{
my_args[0] = "sigperf1";
my_args[1] = "0";
my_args[2] = NULL;
execv("signalSender",my_args);
fprintf(stderr,"signalSender cannot be executed...");
exit(-1);
}
pid2 = fork();
if(pid2 < 0)
{
fprintf(stderr, ": fork failed: %s\n", strerror(errno));
exit(1);
}
if(pid2 == 0)
{
sprintf(str, "%d", pid1);
my_args[0] = "sigperf1";
my_args[1] = str;
my_args[2] = NULL;
// printf("this is converted = %s\n",my_args[1]);
execv(「signalSender",my_args);
fprintf(stderr,"signalSender cannot be executed...");
exit(-1);
}
wid = wait(NULL);
}
的signalSender:
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <ctype.h>
pid_t pid2;
struct sigaction act;
void sighandler(int signum, siginfo_t *info, void *ptr)
{
printf("Received signal %d\n", signum);
printf("Signal originates from process %lu\n",
(unsigned long)info->si_pid);
pid2 = info->si_pid;
}
int main(int argc,char **argv)
{
memset(&act, 0, sizeof(act));
act.sa_sigaction = sighandler;
act.sa_flags = SA_SIGINFO;
sigaction(SIGUSR1, &act, NULL);
pid_t current, pidOther;
current = getpid();
pidOther = atol(argv[1]);
if(pidOther != 0) // we are in the second child
{
kill(pidOther,SIGUSR1); //sending signal from second child to first
}
if(pidOther == 0) // we are in the first child
{
kill(pid2,SIGUSR1);
}
return 0;
}
我認爲你要找的函數是'pause'或'sigsuspend'。 – user3386109