#include <stdio.h>int main()
{printf("--------------------------------------------------\n");system("echo HELLO WORLD");printf("--------------------------------------------------\n");system("ls /");printf("--------------------------------------------------\n");return0;
}
測試程序的輸出結果
--------------------------------------------------
HELLO WORLD
--------------------------------------------------
bin core home lib mnt root snap tmp vmlinuz
boot dev initrd.img lost+found opt run srv usr vmlinuz.old
cdrom etc initrd.img.old media proc sbin sys var
--------------------------------------------------
實現思路:在mysys函數中創建一個新進程,調用execl函數執行命令 代碼實現
#include<stdio.h>#include<sys/wait.h>#include<unistd.h>#include<sys/types.h>#include<stdlib.h>void mysys(char *str){pid_t pid;if(str==NULL){printf("Error:wrong shell string!\n");exit(0);}pid=fork();if(pid==0)execl("/bin/sh","sh","-c",str,NULL);wait(NULL);
}int main(){printf("---------------------------------\n");mysys("echo a b c d");printf("---------------------------------\n");mysys("ls /");printf("---------------------------------\n");return0;
}