Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a custom working directory for a process started with exec

I am calling execv in my C code to launch an executable, but I want to set its working directory to something custom.

For example, in one case, I am launching ls, but it lists the files in my original program's directory. But I want to set the working directory to something custom. How will I achieve it, such that, I'll set it to /usr/bin and ls will list the files in that dir. And don't give me a specific solution for ls, it was just an example.

like image 638
Can Poyrazoğlu Avatar asked Mar 03 '12 16:03

Can Poyrazoğlu


1 Answers

Use chdir(2) after a successful fork(2), before execing:

switch (fork()) {
case 0:
    chdir(newpath); 
    execvp(...);
    break;            
}
like image 143
cnicutar Avatar answered Sep 20 '22 14:09

cnicutar