我想编译这个源代码:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, const char *argv[]) {
While:
printf("MacBook-Pro-...:~ ...$ ");
char command[128];
gets_s(command);
if (strncmp(command, "exit", 4) == 0)
exit(0);
pid_t return_value = fork();
if (return_value == 0) {
int outfile;
if ((outfile = dup(1)) == -1)
return -1;
close(1);
if ((outfile = open("/Users/.../1.txt",
O_WRONLY | O_TRUNC | O_CREAT, 0644)) >= 0) {
execl("/bin/sh", "sh", "-c", command, NULL);
}
close(outfile);
exit(0);
} else {
wait();
FILE *fp;
char str[128];
fp = fopen("/Users/.../1.txt", "r");
while(!feof(fp)) {
if(fgets(str, 126, fp))
printf("%s", str);
}
fclose(fp);
goto While;
}
return 0;
}但我有一些错误:语义问题
系统:
ProductName: Mac : 10.12.1 BuildVersion: 16B2555
Xcode版本8.0 (8A218a)
Apple版本8.0.0 (clang-800.0.38)目标: x86_64-apple-darwin16.1.0线程模型: posix
发布于 2016-10-27 13:17:46
有几个问题:
exit和wait,它可以工作,但是要抑制警告,只需要包含stdlib:#include <stdlib.h>。对于gets_s,您需要做一些额外的操作才能工作(我不知道它是从哪里来的)。wait函数的签名如下所示:int wait(int *),而不给它任何参数。如果不需要从子进程获取退出代码,只需添加0或NULL即可。https://stackoverflow.com/questions/40280174
复制相似问题