linux下进程相关函数

来源:互联网 发布:淘宝360手柄 编辑:程序博客网 时间:2024/04/29 16:36

getpid();返回当前进程的进程标识符。

getppid();返回当前进程的符进程标识符。

exec函数族共有6个函数,这写函数在运行后,会以新的程序取代原来的进程,然后系统会从新的进程开始运行,但是新的进程的PID值会与原来进程的PID相同。

int execl(const char *path,const char *argv0, ...,(char*)NULL);

int execlp(const char *file,const char *argv0, ,,, ,(char *)NULL);

int execle(const char *path,const char *argv0,const char* envp[]);

int execv(const char *path ,const char *argv[]);

int execvp(const char *file ,const char *argv[]);

int execve(const char *path,const char *argv[],const char *envp[]);

其中:

path   准备运行文件的路径名;

arg0: 运行文件的文件名及参数值,最后自变量必须用NULL指针来结束;

argv:要传入的程序参数;

envp:是一个指针,指向特殊环境参数;

file:准备运行的文件名称;

实例:

用execve()函数来运行ls 命令:

#include<unistd.h>

#include<stdlib.h>

#include<stdio.h>

int main(void)

{

         char *args[]={"/bin/ls",NULL};

         execve("/bin/ls",args,NULL);

         perror("execve faied");


}

当然我们也可以用system函数在进程中开始某一进程

int system(const char *string);

system会将/bin/sh -c string 命令行传到execve函数中,来运行自变量string字符串代表的命令。若system在调用/bin/sh时失败返回127,其他原因失败返回-1,自变量string为NULL返回非零值。

实例:

#include<stdio.h>
#include<stdlib.h>
int main(void)
{
    int myret;
    myret=system("ls -l");
    return 0;
}

我们还可以利用fork()函数来产生一个新的子进程,调用fork()函数的进程称为父进程。子进程复制父进程的数据与堆栈空间,并继承父进程的用户代码,组代码。环境变量,已打开的文件代码、工作目录及资源限制,但是子进程并非与父进程用相同的内存空间,因此子进程和父进程并非同步。

pid_t fork(void);成功时则在父进程中返回新简历的子进程代码PID,儿子新建的子进程中返回0;运行失败返回-1;

exit()函数种植进程  void exit(int status); 自变量status称为进程的退出状态。如果为0表示进程成功完成任务,出错则为非零值。