linux C 二、进程

一、进程
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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值