Khi process con gọi exec() và process cha gọi waitpid()

Khi process cha gọi fork, process con sẽ gọi dup2 để chuyển hướng output sau đó gọi exec, còn ở process cha sẽ gọi waipid() để chờ đến khi process con kết thúc. Vấn đề là:

  • khi process con gọi exec(), thì nó sẽ chết ngay (nếu exec thành công), vậy thì process cha thực sự đang đợi cái gì có phải chương trình được gọi từ exec(), hello sẽ trở thành con không ?

  • nếu process cha không gọi waitpid() => process cha kết thúc trước khi hello chạy xong => chương trình sẽ không in vào greet.txt, lí do thực sự ở đây là gì? Bởi vì hello.exe chạy hoàn toàn độc lập, process cha chết thì sao lại ảnh hưởng tới nó? Bơi vì process con (process gọi exec) chết đi => description table quay lại mặc định ?

Mình thực sự không hiểu lắm, có ai có thể giúp mình giải thích không?

#define STDOUT 1
void error(char *message);
int main(int argc, char *argv[]) {
	FILE *f = fopen("greet.txt", "w");
	char* name = argv[1];
	pid_t pid = fork();
	if(pid == 0) {
		if(dup2(fileno(f), STDOUT) == -1)
			error("can't redirct the output");
		if(execl("C:\\Users\\hello.exe", "C:\\Users\\hello.exe", name, NULL) == -1)
			error("can't run the hello program");
	}
	fprintf(stdout, "test if child process redirects the stdout of its parents\n");
// kết quả la không
	fclose(f);
	int pid_status;
	if(waitpid(pid, &pid_status, 0) == -1)
		error("error waiting for process");
	return 0;
}

void error(char *message) {
	fprintf(stderr, "%s : %s\n", message, strerror(errno));
	exit(1);
}
int main(int argc, char* argv[]) {
        sleep(15000); // để chương trình chạy lâu hơn
	printf("hello %s\n", argv[1]);
	return 0;
}
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?