从标准输入读命令并执行

从标准输入读命令并执行

<span style="font-size:14px;">#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
#include<string.h>
#define MAXSIZE 4096
int main()
{
	char buf[MAXSIZE];
	pid_t pid;
	int status;

	printf("%% ");
	while(fgets(buf,MAXSIZE,stdin) != NULL)
	{
		if(buf[strlen(buf) - 1] == '\n')
			buf[strlen(buf)-1] = 0;
		if((pid = fork() ) < 0)
		{
			printf("fork error\n");
			exit(1);
		}
		else if(pid == 0)
		{
			execlp(buf,buf,(char*)0);
			printf("couldn't execute: %s\n",buf);
			exit(127);
		}
		if((pid = waitpid(pid,&status,0)) < 0)
		{
			printf("waitpid error\n");
			exit(1);
		}
		printf("%% ");
	}
	exit(0);
}</span>

1. 标准 I/O函数fgets用于从终端读入一行数据
2. 由于execlp函数要求参数以null结尾,所以用strlen函数求出buf长度用于替换\n为null
3. fork函数用于创建一个新的进程。fork函数向父进程返回新子进程的进程ID,对子进程则返回0。fork被调用一次但返回两次
4. execlp用于执行读入的命令。
5. waitpid函数返回子进程的终止状态(status变量)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值