一、进程
1.1 fork() 缺点是父子进程执行的是相同的函数,并且执行完
退出的时候需要用 wait()去退出,不然会出现僵尸进程占用
系统资源。
1.2 exec函数族,父进程创建子进程,子进程实现Exec函数
#include <unistd.h>
int execl(const char *path, const char *arg, …);
int execlp(const char *file, const char *arg, …);
成功时执行指定的程序;失败时返回EOF
path 执行的程序名称,包含路径
arg… 传递给执行的程序的参数列表
file 执行的程序的名称,在PATH中查找
execl函数可以用来在代码中使用linux命令
如 execlp(“ls”, “ls”, “-a”, “-l”, “./”, NULL)
但exec函数下面自己写的都不会执行
#include <unistd.h>
int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
成功时执行指定的程序;失败时返回EOF
arg… 封装成指针数组的形式
如 if (execv(“/bin/ls”, arg) < 0) {
perror(“execv”);
}
1.3 system函数,父子进程实现不一样的功能,
并且自己的函数还能接着往下跑
#include <stdlib.h>
int system(const char *command);
成功时返回命令command的返回值;失败时返回EOF
当前进程等待command执行结束后才继续执行,但是
system本身并不能获取调用的函数的输出参数,通过管道
自己去写一个类似的system
system获取linux内核指令参数函数(自己写的):
#include “stdlib.h”
#include “unistd.h”
#include “stdio.h”
#include “string.h”
#define MAXLEN 1024
//调用系统命令,并获取输出(改进 system)
//input :要调用的系统命令
//output :调用系统命令后的输出
//maxlen : 最大输入指令长度
int mysystem(char *input,char *output,int maxlen)
{
if(NULLinput || NULLoutput) //输入输出为空直接退出-1
return -1;
int reslen;
FILE *stream;
memset(output,0,maxlen);
//创建管道,并且将input里内容写入管道
stream = popen(input,“r”);
//从管道中独处数据,并写入output
reslen = fread(output,sizeof(char),maxlen,stream);
pclose(stream);
return reslen;
}
int main(int argc,char **argv)
{
if(argc!=2)
{
printf(“please input as need \n”);
exit(1);
}
char output[MAXLEN];
mysystem(argv[1],output,MAXLEN);
printf(“cmd %s result is %s \n”,argv[1],output);
return 0;
}