exec 函數用於在目前的 process 中啟動一個新的程式,取代目前 process 的執行。 也就是成功執行後,原來的程式碼將不再執行,因為目前 process 已被新程式取代。 如果要繼續執行原本的程式,可以使用 fork 讓 exec 在 child process 中執行 以下為使用 `execvp` 的程式碼 ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <string.h> #define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__) int main(int argc, char const *argv[]) { pid_t p; int rc = 0; printf("PID of %s = %d\n", __FILENAME__, getpid()); p = fork(); if (p == -1) { perror("fork"); rc = 1; goto _end; } if (p == 0) { char *args[] = {"/bin/date", "--rfc-3339=s", NULL}; printf("child process\n"); if (execvp(args[0], args) == -1) { perror("Error executing execvp"); } printf("This won't be printed if execvp succeeds\n"); rc = 1; } else { printf("parent process\n"); } _end: return rc; } ``` output ``` PID of main.c = 7636 parent process child process 2023-08-04 23:43:34+08:00 ``` REF: execlp、execvp用法與範例: https://burweisnote.blogspot.com/2017/08/execlpexecvp.html
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up