如何输出进程ID:
当需要从 C 或 C++程序中使用进程 ID 的时候,应该始终使用<sys/types.h>中定义的
pid_t 类型。程序可以通过 getpid()系统调用获取自身所运行的进程的 ID,也可以通过
getppid()系统调用获取父进程 ID。例如下面一段程序输出了程序运行时的进程
ID 和父进程 ID。
#include <stdio.h>
#include <unistd.h>
int main()
{
printf ("The proces ID is %d\n", (int) getpid ());
printf ("The parent process ID is %d\n", (int) getppid ());
return 0;
}
如何创建进程:
创建进程有两种方法
1.使用system
C 标准库中的 system 函数提供了一种调用其它程序的简单方法。利用 system 函数调用
程序结果与从 shell 中执行这个程序基本相似。事实上,system 建立了一个运行着标准
Bourne shell(/bin/sh)的子进程,然后将命令交由它执行。
例:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int return_value;
return_value = system("ls -l /");
return return_value;
}
2.使用fork()与exec()
DOS 和 Windows API 都包含了 spawn 系列函数。这些函数接收一个要运行的程序名作
为参数,启动一个新进程中运行它。Linux 没有这样一个系统调用可以在一个步骤中完成这
些。相应的,Linux 提供了一个 fork 函数,创建一个调用进程的精确拷贝。Linux 同时提供
kill 命令还可以用于对进程发送其它的信号。了另外一系列函数,被称为 exec 族函数,使一个进程由运行一个程序的实例转换到运行另
外一个程序的实例。要产生一个新进程,应首先用 fork 创建一个当前进程的副本,然后使
用 exec 将其中一个进程转为运行新的程序。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t child_pid;
printf("The main program proces ID is %d\n",(int)getpid());
child_pid = fork();
if(child_pid!=0){
printf("this is the parent process, with id %d\n",(int)getpid());
printf("the child's id is %d\n",(int)child_pid);
}
else
printf("this is the child process,with ID %d\n",(int)getpid());
return 0;
}