[英]sending signal between two child process
我在主程序中從父級創建了兩個子級。 第一個和第二個孩子在創建之后執行程序(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);
}
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;
}
您在這里有一個同步問題。
兩個子進程大致在同一時間啟動。 因此,您無法預測哪個會先kill
另一個。 如果第一個孩子先運行kill
,它將作為pid傳遞0
,這將殺死進程組中的每個進程。 同樣,每個子進程在調用kill
之后立即退出,因此一個進程可能在另一個進程有機會向其發送信號之前退出。
您需要介紹某種類型的同步方法。 一種簡單的方法是在調用kill
之前使第二個進程短暫sleep
,以使第一個進程有啟動的機會。 同樣,第一個進程應該調用pause
,它將告訴它等待直到收到信號。
完成此操作后,每個進程都可以調用pause
和kill
循環來回移動。
if(pidOther != 0) // we are in the second child
{
sleep(1); // wait for first child to start
kill(pidOther,SIGUSR1); //sending signal from second child to first
for (i=0;i<5;i++) {
pause();
kill(pidOther,SIGUSR1);
}
}
if(pidOther == 0) // we are in the first child
{
pause(); // wait until we get a signal from the second child
kill(pid2,SIGUSR1);
for (i=0;i<5;i++) {
pause();
kill(pid2,SIGUSR1);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.