Github?
5.1
# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>
# include <sys/wait.h>
int main(){
int x = 0;
int rc = fork();
if(rc < 0){
printf("failed.\n");
}else if (rc == 0)
{
printf ("child x is %d \n",x);
x = 3;
printf ("child x has changed to %d \n",x);
}else
{
x = 100;
printf("father x is %d \n",x);
}
exit(1);
return 0;
}
這是我寫的代碼片段,輸出的結果:
father x is 100
child x is 0
child x has changed to 3
可以看到,雖然看起來執行了父進程,然後執行子進程。並且訪問了x
。但是子進程在一開始的時候所能看到的x
的值依舊是0.
這就說明這種值得改變,並不會跨越進程實現
5.2
ifstream input;
ofstream output;
int main(){
input.open("./5.2.txt");
output.open("./5_2.txt");
int rc = fork();
string temp;
if(rc < 0){
printf("failed.\n");
}else if (rc == 0)
{
input >> temp;
cout << "child.\n" << temp << '\n';
output << "child.\n";
exit(1);
}else
{
input >> temp;
cout << "father.\n" << temp << '\n';
output << "father.\n";
exit(1);
}
return 0;
}
輸出結果:
father.
child.
hello,world.
這個時候我們看到了,只有一個進程成功的獲取了這個文件的內容。打開文件"5_2.txt"發現,兩個進程都可以成功的寫入文本
5.4
execl,execlp,execle(都帶“l”)的參數個數是可變的,參數以一個空指針結束。
execv、execvp和execvpe的第二個參數是一個字符串數組,新程序在啓動時會把在argv數組中給定的參數傳遞到main
所以我們構建的c程序:
int main(){
int rc = fork();
if(rc<0)
{
cout << "failed.\n";
exit(1);
} else if(rc==0){
cout << "child.\n" ;
execl("/bin/ls","ls","-l",NULL);
execle("/bin/ls","ls","-l",NULL,NULL);
execlp("/bin/ls","ls","-l",NULL);
exit(1);
} else{
cout << "father\n" ;
char *v[] = {"ls","-l",NULL};
execve("/bin/ls",v,NULL);
execv("/bin/ls",v);
execvp("/bin/ls",v);
exit(1);
}
return 0;
}
其中的v
就是我設定的一個向量(vector),用來存儲 l
系列函數中公用的部分"ls","-l",NULL
。
這段程序在命令行下運行的結果:
father
child.
total 20
-rwxrwxrwx 1 syy syy 425 Oct 15 16:57 5.1.c
-rwxrwxrwx 1 syy syy 652 Oct 15 17:18 5.2.cpp
total 20
-rwxrwxrwx 1 syy syy 12 Oct 15 17:07 5.2.txt
-rwxrwxrwx 1 syy syy 628 Oct 15 18:56 5.4.cpp
-rwxrwxrwx 1 syy syy 425 Oct 15 16:57 5.1.c
-rwxrwxrwx 1 syy syy 15 Oct 15 17:14 5_2.txt
-rwxrwxrwx 1 syy syy 652 Oct 15 17:18 5.2.cpp
-rwxrwxrwx 1 syy syy 3288 Oct 15 18:57 A.md
-rwxrwxrwx 1 syy syy 12 Oct 15 17:07 5.2.txt
-rwxrwxrwx 1 syy syy 13192 Oct 15 18:57 a.out
-rwxrwxrwx 1 syy syy 628 Oct 15 18:56 5.4.cpp
-rwxrwxrwx 1 syy syy 15 Oct 15 17:14 5_2.txt
-rwxrwxrwx 1 syy syy 3288 Oct 15 18:57 A.md
-rwxrwxrwx 1 syy syy 13192 Oct 15 18:57 a.out
觀察到這裏雖然每一條輸出的都有兩次,但是並不是嚴格的一個進程執行之後再執行另一個。同時會發現,每次編譯再運行出來的結果也是不太一樣的。
說明
後面的c的頭文件和第一個一致,但是我也用來c++