【发布时间】:2016-10-04 17:25:03
【问题描述】:
我在主程序中从父级创建了两个子级。第一个和第二个孩子在创建后执行一个程序(signalSender)(连同另一个孩子的 pid 作为参数)。 signalSender 具有信号处理程序,用于在进程之间发送信号。当第一个孩子执行 signalShooter 时,第二个孩子的 pid 作为参数给出为零。当第二个孩子执行 sigShooter 时,第一个孩子的 pid 作为参数给出。
1) 我想在第二个孩子向第一个孩子发送信号后通过信号处理程序找到第一个孩子的 pid。我试图将它保存到全局变量 pid_t pid2 但它不起作用。
2)我还必须在这两个孩子之间发送信号 100 次,但我不知道在哪里使用“for loop”和“wait”信号。
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);
}
信号发送者:
#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。
标签: c