1、获取进程的id
头文件:
#include <sys/types.h>
#include <unistd.h>
函数原型:
获取本进程ID
pid_t getpid(void)
获取父进程ID
pid_t getppid(void)
获取用户ID
pid_t getuid(void)
例:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
printf ("当前进程 Id: %d\n", getpid());
printf ("当前父进程Id: %d\n", getppid());
printf ("当前用户 Id: %d\n", getuid());
while (1);
return 0;
}
2、进程创建fork()
头文件:
#include <unistd.h>
pid_t fork(void)
功能:
创建子进程
fork的奇妙之处在于它被调用一次,却返回两次,它可能有三种不同的返回值:
1、在父进程中,fork返回新创建的子进程的PID;
2、在子进程中,fork返回0;
3、如果出现错误,fork返回一个负值。
例:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
pid_t pid = fork();
if (pid == -1)
{
perror ("fork");
return -1;
}
if (pid > 0) // 父进程
{
printf ("我是父进程,pid = %d\n", getpid());
}
else if (pid == 0) // 子进程
{
printf ("我是子进程,pid = %d\n", getpid());
}
while (1);
return 0;
}
补充:vfork()
1、vfork 的子进程必须要显示调用 exit();
2、vfork 子进程和父进程共享数据段;
3、vfork 的子进程先于父进程执行,子进程执行完,CPU才能调度到父进程。
示例:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int count = 0;
pid_t pid = vfork();
if (pid < 0)
{
perror("vfork");
return -1;
}
count++;
if (pid > 0) // 父进程
{
printf ("我是父进程,pid = %d count = %d\n", getpid(), count);
}
else if (pid == 0) // 子进程
{
printf ("我是子进程,pid = %d count = %d\n", getpid(), count);
while (1);
exit(0);
}
return 0;
}
3、exec函数族
exec的作用:
exec用被执行的程序替换调用它的程序
exec与fork的区别:
fork:创建一个新的进程,产生一个新的PID
exec:启动一个新程序,替换原有的进程,因此进程的PID不会改变。
(1)execl
头文件
#include <unistd.h>
函数原型
int execl(const char * path, const char* arg1,...)
参数:
path : 被执行程序名(含完整路径)。arg1 - argn: 被执行程序所需的命令行参数,含程序名。以空指针(NULL)结束。
示例:
#include <stdio.h>
#include <unistd.h>
int main()
{
execl ("/bin/ls", "ls", "-al", "/home", NULL);
return 0;
}
(2)execlp
头文件
#include <unistd.h>
函数原型
int execlp(const char * path, const char* arg1,...)
参数:
path : 被执行程序名(不含路径,将从path环境变量中查找该程序)。
arg1 - argn: 被执行程序所需的命令行参数,含程序名。以空指针(NULL)结束。
示例:
#include <stdio.h>
#include <unistd.h>
int main()
{
int ret = execlp("file", "file", NULL);
if (ret == -1)
{
perror("execl");
return -1;
}
return 0;
}
(3)execv
头文件
#include <unistd.h>
函数原型
int execv(const char * path, const char *argv[])
path : 被执行程序名(含完整路径)。
argv[]: 被执行程序所需的命令行参数数组。
示例:
#include <stdio.h>
#include <unistd.h>
int main()
{
char *a[] = {"file", NULL};
int ret = execv("file", a);
if (ret == -1)
{
perror("execl");
return -1;
}
return 0;
}
(4)system
头文件:
#include <stdlib.h>
函数原型:
int system(const char* string)
功能:
调用fork产生子进程,由子进程来调用 /bin/sh -c string来执行参数string所代表的命令
示例:
int main()
{
printf ("hellp world\n");
sleep(1);
// 在内部fork()一个子进程,调用 /bin/sh -c string来执行
system("ps -ef | grep a.out");
return 0;
}