本文简单介绍Unix程序和进程
程序是一个存储在磁盘上某个目录中的可执行文件,内核使用exec函数将程序读入内存并执行
程序的执行实例被成为进程
Unix保证每一个进程都有一个唯一的数字标志符,称为进程ID,其总是一个非负整数
举个例子:
以下程序打印进程ID
#include "apue.h"
int
main(void)
{
printf("hello world from process ID %ld\n", (long)getpid());
exit(0);
}
getpid返回一个pid_t数据类型
进程控制
主要有三个函数:fork、exec、waitpid
举个例子:
#include "apue.h"
#include <sys/wait.h>
int
main(void)
{
char buf[MAXLINE];
pid_t pid;
int status;
printf("%% ");
while(fgets(buf, MAXLINE, stdin) != NULL) {
if(buf[strlen(buf) - 1] == '\n')
buf[strlen(buf) - 1] = 0;
if((pid = fork()) < 0) {
err_sys("fork error");
} else if(pid == 0) {
execlp(buf, buf, (char*)0);
err_ret("couldn't execute: %s", buf);
exit(127);
}
if((pid = waitpid(pid, &status, 0)) < 0)
err_sys("waitpid error");
printf("%% ");
}
exit(0);
}
子进程调用execlp执行新程序文件,而父进程希望等待子进程终止,通过调用waitpid实现
在终端运行结果如下:
wu@ubuntu:~/opt/Cproject/apue/cp1$ ./a.out
% date
Mon Mar 7 16:09:34 PST 2016
% who
wu :0 2016-03-05 23:12 (:0)
wu pts/0 2016-03-07 04:05 (:0)
% pwd
/home/wu/opt/Cproject/apue/cp1
% ls
a.out apue.h b.out control.c copy2.c copy.c copy.c~ data error.c myls.c printID.c
线程和线程ID
一个进程内的所有线程共享同一地址空间、文件描述符、栈以及进程相关的属性,线程也有ID标识,但是线程ID只在它所属的进程内起作用

Comments