父进程从终端读取要执行的命令,并交给子进程执行。父进程等待子进程结束,并打印子进程的返回值。
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
char cmd[256];
// 分割字符串函数
char** split(char *srcStr, char delim, int *num) {
*num = 1;
int srcStrlen = strlen(srcStr);
char **res = (char **)malloc(sizeof(char*) * (srcStrlen+1));
res[0] = (char *)malloc(sizeof(char) * srcStrlen);
memset(res[0], 0, strlen(res[0]));
int k = 0;
for (int i = 0, j = 0; i < strlen(srcStr); i++) {
if (srcStr[i] != delim) {
res[k][j++] = srcStr[i];
} else {
k++; j = 0;
res[k] = (char *)malloc(sizeof(char) * srcStrlen);
memset(res[k], 0, strlen(res[k]));
}
}
*num = k+1;
res[*num] = (char *)malloc(sizeof(char)*srcStrlen);
memset(res[*num], 0, strlen(res[*num]));
res[*num] = 0;
return res;
}
void free2dArray(char **arr, int rows) {
for (int i = 0; i < rows; i++) {
free(arr[i]);
}
free(arr);
}
int main() {
int rtn;
int errorno;
while(1) {
printf(">");
fgets(cmd, 256, stdin);
cmd[strlen(cmd)-1] = 0;
if (fork() == 0) {
int segNum = 0;
// 分割字符串,得到命令的参数
char **argv = split(cmd, ' ', &segNum);
errorno = execvp(argv[0], argv);
free2dArray(argv, segNum);
perror(cmd);
exit(errorno);
} else {
wait(&rtn);
printf("[Child process] return %d\\n", rtn);
}
}
return 0;
}