Federico Zucchi
Federico Zucchi

Reputation: 33

execve on linux, execute from arguments

I need to create a program that allows the user to execute a command passed as argument using execve in linux. I'm not sure about the syntax of the execve command. I wrote the program but it doesn't work with multiple arguments and I can't figure out why.

#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;
}

A command that doesn't work using this code is

cp file1.txt file2.txt

Can someone help me?

Upvotes: 0

Views: 2884

Answers (1)

Robert
Robert

Reputation: 36903

This version is corrected:

#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;
}

Example:

$ ./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

Example 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

I've added #include <unistd.h> because I needed it.

I recommend you to do more printf in order to understand and troubleshoot.

Edit As @jonathan-leffler say, you can use execvp to be able to exec programs using 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;
}

Example:

▶ ./a.out ls
I'm the son woth PID= 5056
Program: ls
a.c a.out
Process terminated with status = 0

Upvotes: 1

Related Questions