getpid()返回父ID

时间:2014-03-16 16:49:46

标签: c process signals fork

我已经编写了以下代码作为练习来理解时间信号,但是当我从孩子调用getpid()函数时,我得到了意外的输出,这给了我父进程ID!

这是输出中的一个样本:

Im the parenet  6355
 I'm , the child 6365 
 Okay , Wait a minute !!! ,  my ip is 6355 

这是代码:

#include <stdlib.h>
#include<stdio.h>
#include <signal.h>
#include <time.h>
void function(int ) ;
void catch_alarm_signal() ; 
void catch_alarm_signal()
{
    printf("Okay , Wait a minute !!! ,  my ip is %d \n " , getpid());
    signal(SIGALRM , catch_alarm_signal);
}
void function(int Read)
{
    signal(SIGALRM , catch_alarm_signal);
    sleep(15) ;
    char string[1] ;
    //read(Read , string , 1 ) ;
    printf("And my input is %s \n" , string) ;
    exit(0);
}
int main()
{
    int fd[2] ;
    //pipe(fd);
    int i   ,pid;
    signal(SIGALRM , catch_alarm_signal);
    for(i =  0 ; i < 10 ; i++)
    {
        pid = fork() ; 
        if(pid == 0)
        {
            printf("I'm , the child %d \n" , getpid());
            function(fd[0]);
            i = 10 ;
        }
        else 
        {
            printf("Im the parenet  %d\n " , getpid());
        }   
    }
    for(i = 0 ; i < 10 ; i++)
    {
        alarm(1) ; 
        wait();
    }
    //write(fd[1] , "5" , 1);   

    return 0 ;
}

0 个答案:

没有答案