如何使用execlp()查找pid?

时间:2019-03-27 09:26:48

标签: c linux exec

getpid()给我一个进程的PID。但是现在我想使用execlp()命令找到PID,并打印PID。但我无法解决。帮助。

#include <stdio.h>     //my code so far
#include <unistd.h>
#include <sys/types.h>
int main()
{
   execlp("/usr/include","/usr/include",getpid(),(char *)0);
}

1 个答案:

答案 0 :(得分:0)

我认为您在设计中缺少一步。您正在尝试使用execlp()来调用库函数getpid(),但这是行不通的。如果您需要通过调用execlp()来获取进程的PID,则需要一个程序来调用。

因此,首先创建一个简单的程序以打印出其PID:

#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
   printf( "%s %d\n", argv[1], getpid()) ;
}

调用此printpid.c并将其编译为名为printpid的可执行文件。然后,您可以使用一个程序来执行此操作:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
   pid_t pid = fork() ;
   if ( pid == 0 )
   {
      execlp("./printpid", "printpid", "child", (char *)0) ;
   } else {
      execlp("./printpid", "printpid", "parent", (char *)0) ;
   }

   return 0 ;
}

将其编译为名为forkprocess say的可执行文件,并确保它和printpid程序位于同一目录中。当您运行forkprocess时,它将运行两次printpid,并且printpid显示该进程的PID。为了弄清楚发生了什么,我正在向printpid传递参数,以显示是从父进程还是由调用fork()创建的子进程调用它。