[c] How to use execvp()

The user will read a line and i will retain the first word as a command for execvp.

Lets say he will type "cat file.txt" ... command will be cat . But i am not sure how to use this execvp(), i read some tutorials but still didn't get it.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char *buf;
    char command[32];
    char name[32];
    char *pointer;
    char line[80];
    printf(">");

    while((buf = readline(""))!=NULL){   
        if (strcmp(buf,"exit")==0)
        break;

        if(buf[0]!=NULL)
        add_history(buf);

        pointer = strtok(buf, " ");
        if(pointer != NULL){
            strcpy(command, pointer);
        }

        pid_t pid;

        int  status;

        if ((pid = fork()) < 0) {     
            printf("*** ERROR: forking child process failed\n");
            exit(1);
        }
        else if (pid == 0) {          
            if (execvp(command, buf) < 0) {     
                printf("*** ERROR: exec failed\n");
                exit(1);
            }
        }
        else                                  
        while (wait(&status) != pid)       
            ;
        free(buf);
        printf(">");
    }///end While
    return 0;
}

This question is related to c shell fork execvp

The answer is


In cpp, you need to pay special attention to string types when using execvp:

#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
#include <unistd.h>
using namespace std;

const size_t MAX_ARGC = 15; // 1 command + # of arguments
char* argv[MAX_ARGC + 1]; // Needs +1 because of the null terminator at the end
// c_str() converts string to const char*, strdup converts const char* to char*
argv[0] = strdup(command.c_str());

// start filling up the arguments after the first command
size_t arg_i = 1;
while (cin && arg_i < MAX_ARGC) {
    string arg;
    cin >> arg;
    if (arg.empty()) {
        argv[arg_i] = nullptr;
        break;
    } else {
        argv[arg_i] = strdup(arg.c_str());
    }
    ++arg_i;
}

// Run the command with arguments
if (execvp(command.c_str(), argv) == -1) {
    // Print error if command not found
    cerr << "command '" << command << "' not found\n";
}

Reference: execlp?execvp?????


Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"

Examples related to fork

How to use execvp() Example of waitpid() in use? How to make parent wait for all child processes to finish? fork: retry: Resource temporarily unavailable fork() child and parent processes How to kill a child process by the parent process? How to use shared memory with Linux in C The difference between fork(), vfork(), exec() and clone() fork() and wait() with two child processes Redirecting exec output to a buffer or file

Examples related to execvp

How to use execvp()