简体   繁体   中英

Calling “bash [script name]” in C

I am trying to run a bash script to generate an OpenSSL certificate. I have the bash script in the same directory as my c code.

Relevant C code:

pid_t pid = fork();
if(pid > 0){
    char* arr[] = {"./generate_cert.sh", "direct"};
    int succ = execv(arr[0], arr);
    printf("succ: %d\n", succ);
    exit(1);
}else if(pid < 0){
    printf("Fork failed\n");
    exit(-1);
}

generate_cert.sh, My test bash script which I will eventually expand is:

#!/bin/bash
echo "$1"

It seems I have a permission denied with./generate_cert.sh. I need to instead run bash generate_cert.sh. How do I do this with execv?

According to the execv man page, the array must be terminated by a null pointer.

So something along the lines of this (untested):

  char* arr[] = {"./generate_cert.sh", "direct",NULL};
  int succ = execv(arr[0], arr);

Edit :

OP's problem turned out to be the execute bit wasn't set on the script file. Which was solved by chmod +x generate_cert.sh , however another alternative would be to make the execv call to /bin/bash instead. Ie something along the lines of.

char* arr[] = {"/bin/bash", "./generate_cert.sh", "direct",NULL};
int succ = execv(arr[0], arr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM