本文共 541 字,大约阅读时间需要 1 分钟。
用mysystem()函数来说明被调用的系统函数system是如何被实现出来的!其实是调用了linux里面的shell命令解释器来进行命令调用的,是通过fork()函数创建一个父进程和子进程,
然后在子进程中进程调用execl()来引入shell解释器,从而实现命令解析的功能!
下面请看代码吧
#include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<unistd.h> #include<string.h> void mysystem(char *string); int main() { char *string; char str[1024]; string=str; gets(string); mysystem(string); } void mysystem(char *string) { pid_t pid; pid=fork(); if(-1==pid) { printf("error!\n"); } else if (pid==0) { execl("/bin/sh","sh","-c",string,NULL); exit(1); } else { exit(1); } }
转载地址:http://oaqbb.baihongyu.com/