Linux环境编程--进程


查看正在运行的进程

#ps -ef

#ps ax

可以看到状态

查看nice值

#ps -l

#ps -f

system函数

传递命令,如同在shell中执行

char * p="ps ax";

system(p);

或者 ="ps ax &";//ps一启动shell就返回

execl,execlp,execle函数

exec启动一个新程序,替换原有的进程,因此这个新的被exec执行的进程的PID不会改变,和调用exec函数的进程一样。

表头文件
    #include<unistd.h>
execlp("ps","ps","ax",0);

参考: exec函数族的使用

pid_t是什么?

是Linux下的进程号类型,也就是Process ID _ Type 的缩写。 其实是宏定义的unsigned int类型

sys/types.h:typedef short pid_t; /* used for process ids */

pid_t pid;

fork()函数

产生新进程

pid=fork();

在语句pid=fork()之前,只有一个进程在执行这段代码,但在这条语句之后,就变成两个进程在执行了。

该函数被调用一次,但返回两次。两次返回的区别是子进程的返回值是0,而父进程的返回值则是新子进程的进程ID。

perror ( )函数

用 来 将 上 一 个 函 数 发 生 错 误 的 原 因 输 出 到 标 准 设备 (stderr)

puts()函数

按行将字符串送到流stdout中 

代码:

  1. #include <sys/types.h>   
  2. #include <unistd.h>   
  3. #include <stdio.h>   
  4. #include <stdlib.h>   
  5.   
  6. int main()  
  7. {  
  8.     pid_t pid;  
  9.     char *message;  
  10.     int n;  
  11.   
  12.     printf("fork program starting\n");  
  13.     pid = fork();  
  14.     switch(pid)   
  15.     {  
  16.     case -1:  
  17.         perror("fork failed");  
  18.         exit(1);  
  19.     case 0:  
  20.         message = "This is the child\n";  
  21.         printf(message);  
  1.     n = 5;  
  2.     break;  
  3. default:  
  4.     message = "This is the parent\n";  
  5.     printf(message); 
  1.     n = 3;  
  2.     break;  
  3. }  

相关内容