linux 学习笔记2

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mcl2840072208/article/details/81149175

程序和进程

1.程序

程序:存储在磁盘上某个目录上的可执行文件。

2.进程和进程ID

程序的执行实例被称为进程(windows 叫做任务),每个进程都有一个进程ID

打印进程ID

#include "apue.h"
int main(void)
{
    pritnf("hello world from process ID %ld\n",(long)getpid());
    return 0;
}

3.进程控制

介绍3个主要函数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;//execlp()函数要求参数是以NULL结尾的
if((pid=fork())<0)
    err_sys("fork error");
else if(pid==0)
{
    execlp(buf,buf,(char*)0);
    err_ret("Counldn't execute : %s",buf);
    exit(127);

}
if((pid=waitpid(pid,&status,0))<0)
    err_sys("waitpid error");
printf("%% ");
}
return 0;
}

调用fork创建一个进程,新进程是调用进程的副本,称调用进程为父进程,新创建的进程 为子进程。fork对父进程返回一个新的进程ID,对子进程返回0

猜你喜欢

转载自blog.csdn.net/mcl2840072208/article/details/81149175