system函数(fork,execlp)

system 函数和有同等机能的函数(mysystem)的示例。
execlp(execvp,..)函数一实行参数的命令和指定参数就将执行,但是执行后,相应程序将终止。
如果想在其执行后,仍继续进行程序处理动作,就要通过fork生成子进程,在那个子进程内执行execlp等命令。execlp函数执行结束后,即使子进程终了后,其父进程仍然能够继续执行相应处理。
execlp 函数中,用通常的shell执行pipe和Redirection处理( |  etc.)和通过正规表现(? * etc.)不能进行复杂的处理.如要进行复杂的处理,通过shell command(/bin/sh etc.)来执行. 例:
  execlp("/bin/sh","/bin/sh","-c","ls | wc > output.txt",NULL);
例如,mysystem()函数的执行例和根据mysystem()函数的执行结果(exit status)发生分歧处理的例子。
system函数(fork,execlp)(list_76.c)
#include stdio.h>
#include stdlib.h>
#include sys/types.h>
#include sys/wait.h>
int mysystem(char* cmd)
{
    int child,status;
    if ((child = fork())  0) {
        perror("fork");
        return EXIT_FAILURE;
    }
    if(child == 0){
        execlp("/bin/sh","/bin/sh","-c",cmd,NULL);
        return EXIT_FAILURE;
    } else {
        if(wait(&status)  0) {
            perror("wait");
            exit(1);
        }
    }
    return status;
}
int main(int argc,char* argv[])
{
    int status;
    char cmd[256];
    if(argc  4) {
        printf("usage: %s \"test-rule\" \"true command\" \"false command\"\n",argv[0]);
        return 0;
    }
    printf("**test of mysystem\n");
    mysystem("cat list_76.c | wc");
   
    printf("**execute shell rule\n");
    sprintf(cmd,"test %s;",argv[1]);
    status = mysystem(cmd);
    if(status) mysystem(argv[3]);
    else mysystem(argv[2]);
   
    return 0;
}


执行结果

Gami[178]% ./list_76.exe
usage: ./list_76.exe "test-rule" "true command" "false command"
Gami[179]% ./list_76.exe "-f makefile" "head makefile" "ls"
**test of mysystem
     43 90 840
**execute shell rule --> true 的执行[存在 makefile ]
SRC = list_76
OBJS = $(SRC).o
COMP = gcc
FLAG = -lm -Wall
LANG = c
all: $(OBJS)
        $(COMP) -o $(SRC) $(OBJS) $(FLAG)
        ./$(SRC)
Gami[180]% ./list_76.exe "-d folder" "head makefile" "ls -F"
**test of mysystem
     43 90 840
**execute shell rule --> false 的执行[名叫folder 的文件夹不存在]
makefile misc/ list_76.c list_76.exe* list_76.o
Gami[181]%


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/98822/showart_1992370.html
 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值