[英]synchronization between two process in c
I am trying to send signals between two child in alternative way for 100 times. 我试图以替代方式在两个孩子之间发送信号100次。
Here is my snippet of code. 这是我的代码片段。
here is the link to the whole question: sending signal between two child process 这是整个问题的链接: 在两个子进程之间发送信号
But i have synchronization issue in the loop. 但是我在循环中有同步问题。 where is the right position to put the sigsuspend()?
放置sigsuspend()的正确位置在哪里?
#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;
sigset_t mask,oldmask,temp;
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)
{
int i,j,counter = 0,counter2 = 0;
sigemptyset(&mask);
sigemptyset(&temp);
//sigemptyset(&oldmask);
sigaddset(&mask,SIGUSR1);
//sigset_t mask;
memset(&act, 0, sizeof(act));
act.sa_sigaction = sighandler;
act.sa_flags = SA_SIGINFO;
if(sigaction(SIGUSR1, &act, NULL) == -1)
fprintf(stderr, "sigaction failed: %s\n", strerror(errno));
pid_t current, pidOther;
current = getpid();
pidOther = atol(argv[1]);
int k;
for(k = 0;k < 100;k++){
if(pidOther != 0){ // second child
kill(pidOther,SIGUSR1);
sigprocmask(SIG_BLOCK,&mask,&oldmask);
counter++;
printf("2nd child = %d sent signal to 1st child = %d signal number = %d\n",getpid(),pidOther,counter);
//sigprocmask(SIG_BLOCK,&mask,&oldmask);
sigsuspend(&temp);
}
if(pidOther == 0) // fisrt child
{
//pause();
kill(pid2,SIGUSR1);
sigprocmask(SIG_BLOCK,&mask,&oldmask); // was blank
counter++;
printf("\nj=%d 1st child = %d sent signal to 2nd child = %d signal counter = %d\n",j,getpid(),pid2,counter);
printf("test1\n");
sigsuspend(&temp); // was pause()
}
}
return 0;
}
I don't see you calling fork()
anywhere. 我看不到您在任何地方调用
fork()
。 Also taking the process ID of the second process is not the way your program should know about the child process. 同样,获取第二个进程的进程ID也不是您的程序应了解子进程的方式。 Here's a simple example of how to use fork.
这是一个如何使用fork的简单示例。
pid_t pid = fork();
if (pid == 0)
{
// executes only in child process..
// do stuff related what you need to do in child process
}
else
{
// executes only in parent process
// pid variable contains the child process's PID.
// do stuff related what you need to do in parent process
}
// runs in both parent and child.
问题在于,第一个孩子第一次循环时, pid2
为0,因此它将信号发送到进程组中的每个进程(包括自身),这意味着它将立即开始循环,将信号(正好)发送回自身。 ..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.