Why does getpid() return pid_t instead of int?

后端 未结 6 1073
太阳男子
太阳男子 2020-12-23 19:37

What\'s the logic behind calls like getpid() returning a value of type pid_t instead of an unsigned int? Or int? How does

6条回答
  •  梦毁少年i
    2020-12-23 20:03

    Each process in the program has a specific process ID. By calling pid, we know the assigned ID of the current process.Knowing the pid is exceptionally important when we use fork(), because it returns 0 and !=0 values for child and parent copies receptively.These two videos have clear explanations: video#1 Video#2

    An example: Suppose we have the following c program:

    #include 
    #include 
    #include 
    #include 
    
    
    int main (int argc, char *argv[])
    {
    
      printf("I am %d\n", (int) getpid());
      pid_t pid = fork();
      printf("fork returned: %d\n", (int) pid);
      if(pid<0){
        perror("fork failed");
      }
      if (pid==0){
        printf("This is a child with pid %d\n",(int) getpid());
      }else if(pid >0){
        printf("This is a parent with pid %d\n",(int)getpid());
      }
    
      return 0;
    }
    

    If you run it, you will get 0 for child and non zero/greater than zero for the parent.

提交回复
热议问题