#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;
}
}
run this code in linux then, segement falut (core dump)
also when using gdb,
==========================================================
Program received signal SIGSEGV, Segmentation fault. 0x0000003b6572fa96 in __strcmp_sse42 () from /lib64/libc.so.6
==========================================================
why it is not working?
if I type /bin/ls -al (anything without '&') good working
buf type /bin/ls -al & error
If you enter an &
, the variable argv[cnt-1]
will be set to NULL, therefore in if(!strcmp(argv[cnt-1], "exit"))
the first argument of the function strcmp
will be NULL, which will crash the application...
Furthermore your code does not check any buffer overflow, index out of bound, ... This code is quite "dangerous"
This implies, that:
gets
, see https://stackoverflow.com/a/1694042/808101argv
(note: this variable name is maybe not a good one, argv is very often the arguments of the program itself) array is big enough when inserting element in it