如何将乘客儿童的信号发送给出租车 - 儿童? 我有以下C代码:
passengerPid = fork()
if(passengerPid) { //passenger-parents
taxiPid = fork();
if(taxiPid) { //taxi - parents
} else { //taxi - children
}
}
else { //passenger - children
}
答案 0 :(得分:0)
我怎样才能将乘客孩子的信号发送给出租车 - 儿童? 是这是可能的,但问题是你如何得到taxi-children
pid在passenger-children
进程中?一旦你得到那些出租车孩子的pid,为了从另一个过程向一个过程发送信号,你可以使用kill()
功能。使用任何IPC
机制将一个进程的pid
(任何int数据)发送到其他进程。
这是我的解决方案,在此之前通过wait()
& waitpid()
:
/**How can I send a signal form passenger-children to the taxi - children? **/
#include<stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main() {
int passengerPid, taxiPid;
passengerPid = fork();
if(passengerPid) { //passenger-parents
taxiPid = fork();
if(taxiPid) {
//taxi - parents
printf("taxi parents or main parent process : pid = %d ppid = %d\n",getpid(),getppid());
/** parents should wait until all children's got finish
use wait() or waitpid() to collect the children's status **/
int s,ret;
while((ret = wait(&s))!=-1)//if there is no further child, wait returns
{
if(ret == passengerPid) {
if(WIFEXITED(s)) {
printf("passenger children removed after sleep, status is : %d\n",WEXITSTATUS(s));
} else if(WIFSIGNALED(s)) {
printf("passenger children removed forcefully because of signal no : %d \n",WTERMSIG(s));
}
} else if(ret == taxiPid) {
if(WIFEXITED(s)) {
printf("taxi children removed after sleep, status is : %d\n",WEXITSTATUS(s));
} else if(WIFSIGNALED(s)) {
printf("taxi children removed forcefully because of signal no : %d \n",WTERMSIG(s));
}
}
}
printf("all done !! parents is also going to complete \n");
}
else {
//for sending pid of this process
#if 0
int fd = open("data",O_WRONLY | 0664);
if(fd == -1) {
perror("open");
return 0;
}
int w_pid = getpid();
write(fd,&w_pid,4);
close(fd);
#endif
//taxi - children
printf("taxi children : pid = %d ppid = %d\n",getpid(),getppid());
sleep(10);//random delay to observe whether this process got any signal or not ?
exit(1);//sends it's exit status to it's parent process whether it's terminated normally or by any external signal
}
}
else {
//passenger - children
printf("passenger children : pid = %d ppid = %d\n",getpid(),getppid());
printf("sending signal from passenger children to taxi children :\n");
sleep(5);
int pid;
#if 0
int fd = open("data",O_RDONLY | 0664);
if(fd == -1) {
perror("open");
return 0;
}
read(fd,&pid,4);
close(fd);
#endif
printf("pid of child received : %d \n",pid);
kill(pid,SIGKILL);//sending signal no 2 to taxi child, bydefault action of SIGINT will be performed
perror("kill");
printf("passenger children dies after sending signal & completion of delay\n");
exit(0);
}
}
上面的代码如何工作在注释本身中解释。在这两个流程中macro(#if 0)
部分的使用是将pid
的{{1}}发送到taxi-child process
。 启用 宏以观察输出。
我希望它有所帮助。