【发布时间】:2018-05-13 12:05:53
【问题描述】:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
void main(){
int x,y,status, i;
int cnt = 0;
int flag = 0;
char buf[50];
char str[50];
char * argv[10];
char * ptr;
for(i=0; i<10; i++){
printf("$");
gets(buf);
strcpy(str, buf);
ptr = strtok(buf, " ");
while(ptr != NULL){
argv[cnt] = ptr;
cnt++;
ptr = strtok(NULL," ");
}
if(!strcmp(argv[cnt-1], "&")) {
argv[cnt-1] = 0;
flag = 1;
}
else {
argv[cnt] = 0;
}
if(!strcmp(argv[cnt-1], "exit")) exit(0);
x=fork();
if (x==0){
sleep(1);
printf("I am child to execute %s\n", str);
y=execve(argv[0], argv, 0);
if (y<0){
perror("exec failed");
exit(1);
}
}
else {
if(flag == 0) {
wait(&status);
}
}
flag = 0;
cnt = 0;
}
}
然后在 linux 中运行此代码, 段故障(核心转储)
在使用 gdb 时,
================================================ ===========
节目收到信号SIGSEGV, 分段故障。 __strcmp_sse42 () 中的 0x0000003b6572fa96 来自 /lib64/libc.so.6
================================================ ===========
为什么它不起作用?
如果我输入 /bin/ls -al(任何不带'&'的东西) 干得好
buf 类型 /bin/ls -al & 错误
【问题讨论】:
-
OT:不要使用
gets(buf)!请改用fgets(buf, 50, stdin)。 -
无论 Visual Studio 允许什么,来自
main()的唯一有效返回类型是int,而不是void