我正在閱讀作業系統三個簡單的部分。在完成其中一個練習時,我遇到了一個與“write”系統呼叫相關的有趣行為。程式如下,
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <errno.h>
int main()
{
int fd = open("./some_file.txt", O_CREAT | O_WRONLY | O_APPEND, 0777);
int rc = fork();
if (rc < 0)
{
printf("Fork failed\n");
exit(10);
}
else if (rc == 0)
{
write(fd, "the sun shines so bright\n", 26);
}
else
{
wait(NULL);
int e = write(fd, "it's a cold night outside \n", 36);
if (e == -1)
{
printf("error writing to fd, %s", strerror(errno));
exit(-1);
}
}
return 0;
}
由于父行程等待子行程完成,該程式的輸出是,
the sun shines so bright
it's a cold night outside
這是預期的。但是,如果我將要寫入子行程的位元組數從 26 更改為 36,
write(fd, "the sun shines so bright\n", 36);
輸出變為
the sun shines so bright
it's a colit's a cold night outside
_________^ 10 bytes
子行程字串(陽光如此耀眼\n\0)為26位元組。額外的 10 個位元組導致此行為。我為子行程中的 write 陳述句嘗試了不同的值,并且行為是一致的。有人可以解釋為什么會這樣嗎?
uj5u.com熱心網友回復:
有人可以解釋為什么會這樣嗎?
因為write(fd, "the sun shines so bright\n", 26);只有 25 個位元組,然后是不應該寫入的零終止符,但是該零終止符可能只是被您用來顯示檔案的任何內容所忽略,因此它“作業”(偶然地,以一種會破壞的方式如果您以不同的方式顯示檔案并且檔案中間的零終止符沒有被忽略)。
因為write(fd, "the sun shines so bright\n", 36);仍然只有 25 個位元組,然后是不應該寫入的零終止符,然后還有 10 個不應該寫入的垃圾位元組。那個垃圾恰好是一個完全不同的字串的開頭,所以(由于運氣和未定義行為的結合)它實際上寫了“ the sun shines so bright\n”,然后是被忽略的字串終止符,然后是“ it's a col”。
因為write(fd, "it's a cold night outside \n", 36);只有 26 個位元組,然后是不應該寫入的零終止符,然后是不應該寫入的 9 個位元組的垃圾。在這種情況下(由于運氣和未定義行為的結合),我假設垃圾恰好是零。老實說,我很驚訝(由于運氣和未定義行為的結合)它最終沒有寫“ it's a cold night outside \n”,然后是被忽略的零終止符,然后是“ error wri”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/426453.html
