免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2476 | 回复: 0
打印 上一主题 下一主题

system函数(fork,execlp) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-07-10 22:40 |只看该作者 |倒序浏览

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
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP