arrays - Syntax for passing a const char parameter to static char *argv[] in C -


okay, i'm trying build daemon (for debian machine) take command line arguments receives (via cron) , pass them different script files.

the daemon's main()

 int main(int argc , char *argv[])  {         if(argc != 3)         {             exit(0);         }          daemonize(argv[1], argv[2]);      return 0;  } 

and function daemonize has set

int daemonize(const char *cmd1, const char *cmd2) {...} 

the troubling part in daemonize here:

if (strcmp(cmd1,"sample_script") == 0)     {         static char *argv[] = {"/etc/init.d/sample_script", ["%s",cmd2], null };         execv("/etc/init.d/sample_script",argv);         exit(127);     } 

on line

static char *argv[] = {"/etc/init.d/sample_script", ("%s",cmd2), null };

i getting error

initializer element not constant (near initialization ‘argv[1]’)

obviously ("%s",cmd2) wrong. because using "start" works fine.

so, how cmd2 correctly put *argv[]? or else doing wrong?

you need change

static char *argv[] = {"/etc/init.d/sample_script", ["%s",cmd2], null }; 

to

const char *argv[] = {"/etc/init.d/sample_script", cmd2, null }; 

you have remove static keyword. per chapter 6.7.9, c11 standard,

all expressions in initializer object has static or thread storage duration shall constant expressions or string literals.

which says, in c language objects static storage duration have initialized constant expressions or aggregate initializers containing constant expressions.

and, regarding constant expression, chapter 6.6 of same document

a constant expression can evaluated during translation rather runtime, , accordingly may used in place constant may be.

so, in c, variable (name), if declared const never constant expression.


edit:

to resolve latest issue, can try following

  1. change int daemonize(char *cmd1, char *cmd2) {..
  2. use char * const argv[] = {"/etc/init.d/sample_script", cmd2, null };

and can keep rest of code unchanged.


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -