[英]Signal from parent to its child processes in Linux
我將很快寫出我想用我的代碼做什么以及真正的輸出是什么。 我有一個創建兩個子進程的父進程。 兩個進程中的每個進程均從不同文件讀取100字節,子進程1從“ child1.txt”讀取,子進程2從“ child2.txt”讀取。 我想通過使用信號強制在子1之前執行子2。
我創建了兩個子進程並暫停了它們(當它們收到信號時,暫停結束)。 因此,我向孩子2發送了一個信號,然后我向孩子1發送了一個信號。這樣,我希望他們會做我想要的,但他們不做(它始終顯示child1.txt的內容),我聽不懂為什么。
這是代碼
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <fcntl.h>
#include <wait.h>
void my_handler(int signo);
int main(int argc, char *argv[]){
signal(SIGCHLD,my_handler);
pid_t pid[2]; //here is where I save child pid
char buffer[100];
for (int i=0;i<2;i++){
if((pid[i]=fork())==0){
signal(SIGUSR1,my_handler);
int fd,nbyte;
pause();
if(i==0){
fd=open("Child1.txt",O_RDONLY);
}else{
fd=open("Child2.txt",O_RDONLY);
}
nbyte=read(fd,buffer,100);
buffer[nbyte-1]='\0';
write(STDOUT_FILENO,buffer,strlen(buffer));
exit(1);
}
sprintf(buffer,"Child %d\n",(int)pid[i]);
write(STDOUT_FILENO,buffer,strlen(buffer));
}
kill(pid[1],SIGUSR1); //I send a signal to unpause child2
wait(NULL); // wait child 2 to terminate
kill(pid[0],SIGUSR1); //unpause child 1
wait(NULL); // wait child 1 to terminate
}
void my_handler(int signo){
}
下面的建議代碼:
現在建議的代碼:
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <fcntl.h>
#include <wait.h>
#define BUF_SIZE 100
#define NUM_CHILDREN 2
void my_handler(int signo);
int main( void )
{
//signal(SIGCHLD,my_handler);
pid_t pid[ NUM_CHILDREN ] = {0};
char buffer[ BUF_SIZE +1];
for ( int i=0; i<NUM_CHILDREN; i++ )
{
if((pid[i]=fork())==0)
{ // then child
signal(SIGUSR1,my_handler);
int fd;
ssize_t nbyte;
pause();
if(i==0)
{
if( (fd=open("child1.txt",O_RDONLY) ) == -1 )
{
perror( "open to read child1.txt failed" );
exit( EXIT_FAILURE );
}
}
else
{
if( (fd=open("child2.txt",O_RDONLY) ) == -1 )
{
perror( "open to read child2.txt failed" );
exit( EXIT_FAILURE );
}
}
if( (nbyte=read(fd,buffer,100) ) ==-1 || nbyte == 0 )
{
perror( "read failed" );
exit( EXIT_FAILURE );
}
buffer[nbyte]='\0';
write(STDOUT_FILENO,buffer,strlen(buffer));
fflush( stdout );
close( fd );
exit( EXIT_SUCCESS );
}
else if( pid[i] > 0 )
{ // then parent
sprintf( buffer,"Child %d PID %d\n", i, (int)pid[i] );
write( STDOUT_FILENO, buffer, strlen(buffer) );
fflush( stdout );
}
else
{ // fork failed
perror( "fork failed" );
}
}
sleep(1); // allow all child processes to be ready for signal
if( pid[0] > 0 )
{
kill(pid[0],SIGUSR1); //send a signal to unpause child 0
wait( NULL );
}
if( pid[1] > 0 )
{
kill(pid[1],SIGUSR1); //unpause child 1
wait( NULL );
}
}
void my_handler(int signo)
{
(void)signo;
}
child1.txt的內容(請注意,我使用所有小寫字母作為文件名)
123
child2.txt的內容(請注意,我使用所有小寫字母作為文件名)
456
運行這些代碼會導致:
Child 0 6630
Child 1 6631
123
456
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.