execve в Linux, выполнить из аргументов
Мне нужно создать программу, которая позволяет пользователю выполнять команду, переданную в качестве аргумента, используя execve в Linux. Я не уверен насчет синтаксиса команды execve. Я написал программу, но она не работает с несколькими аргументами, и я не могу понять, почему.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
int main(int argc, char **argv)
{
int status;
pid_t pid;
if((pid = fork())>0)
{
///Father process
wait(&status);
printf("Process terminated with status = %d\n",status);
}
else
{
///son process
int i;
char param[100];
printf("I'm the son woth PID= %d\n",getpid());
printf("%s\n",argv[0]);
printf("%s\n",argv[1]);
printf("%s\n",argv[2]);
strcpy(param,"/bin/");
strcat(param,argv[1]);
execve(param,argv,NULL);
exit(-1);
}
return 0;
}
Команда, которая не работает с использованием этого кода
cp file1.txt file2.txt
Кто-нибудь может мне помочь?
1 ответ
Решение
Эта версия исправлена:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
int main(int argc, char **argv)
{
int status;
pid_t pid;
if((pid = fork())>0)
{
///Father process
wait(&status);
printf("Process terminated with status = %d\n",status);
}
else
{
///son process
int i;
char program[100];
printf("I'm the son woth PID= %d\n",getpid());
strcpy(program,argv[1]);
printf("Program: %s\n", program);
execve(program, argv+1, NULL);
exit(0);
}
return 0;
}
Пример:
$ ./a.out /bin/cp a.txt b.txt
I'm the son woth PID= 1590
Program: /bin/cp
/bin/cp
a.txt
b.txt
Process terminated with status = 0
Пример 2:
./a.out /bin/ls
I'm the son woth PID= 3021
Program: /bin/ls
/bin/ls
a.c a.out
Process terminated with status = 0
я добавил #include <unistd.h>
потому что мне это было нужно.
Я рекомендую вам сделать больше printf
для того, чтобы понять и устранить неполадки.
Редактировать Как сказал @jonathan-leffler, вы можете использовать execvp, чтобы иметь возможность запускать программы, используя PATH:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
int main(int argc, char **argv)
{
int status;
pid_t pid;
if((pid = fork())>0)
{
///Father process
wait(&status);
printf("Process terminated with status = %d\n",status);
}
else
{
///son process
int i;
char program[100];
printf("I'm the son woth PID= %d\n",getpid());
strcpy(program,argv[1]);
printf("Program: %s\n", program);
execvp(program, argv+1);
exit(0);
}
return 0;
}
Пример:
▶ ./a.out ls
I'm the son woth PID= 5056
Program: ls
a.c a.out
Process terminated with status = 0