Debian Codegraph @

tests/fork_tests.rs

raw symbols SCIP
1 //! Fork functionality integration tests
2 //!
3 //! This module tests the core `fork()` and `waitpid()` functions.
4 //! These tests verify:
5 //! - Basic fork/waitpid functionality
6 //! - Parent-child process communication via files
7 //! - Multiple child process management
8 //! - Environment variable inheritance across fork
9 //! - Command execution in child processes
10 //! - PID uniqueness between parent and child
11 //! - Proper process synchronization with waitpid
12 //!
13 //! All tests use temporary files for parent-child communication since
14 //! forked processes have separate memory spaces.
15
16 #![allow(clippy::expect_used)]
17 #![allow(clippy::unwrap_used)]
18 #![allow(clippy::panic)]
19 #![allow(clippy::match_wild_err_arm)]
20 #![allow(clippy::similar_names)]
21 #![allow(clippy::uninlined_format_args)]
22 #![allow(clippy::indexing_slicing)]
23
24 mod common;
25
26 use std::{
27 env, fs,
28 process::{Command, exit},
29 thread,
30 time::Duration,
31 };
32
33 use fork::{Fork, fork, waitpid};
34
35 use common::{get_test_dir, setup_test_dir};
36
37 #[test]
38 // Tests basic fork() functionality with waitpid()
39 // Expected behavior:
40 // 1. fork() returns Ok(Fork::Parent(pid)) in parent with child PID
41 // 2. fork() returns Ok(Fork::Child) in child
42 // 3. Child PID is positive
43 // 4. waitpid() successfully waits for child to exit
44 // 5. No zombie processes remain
45 fn test_fork_basic() {
46 match fork() {
47 Ok(Fork::Parent(child)) => {
48 assert!(child > 0, "Child PID should be positive");
49
50 // Wait for child
51 assert!(waitpid(child).is_ok(), "waitpid should succeed");
52 }
53 Ok(Fork::Child) => {
54 // Child just exits
55 exit(0);
56 }
57 Err(_) => panic!("Fork failed"),
58 }
59 }
60
61 #[test]
62 // Tests parent-child communication using files
63 // Expected behavior:
64 // 1. Parent and child have separate memory spaces
65 // 2. Child writes a message to a file
66 // 3. Parent reads the message after child completes
67 // 4. Message content matches what child wrote
68 // 5. Demonstrates file-based IPC pattern
69 fn test_fork_parent_child_communication() {
70 let test_dir = setup_test_dir(get_test_dir("fork_communication"));
71 let message_file = test_dir.join("message.txt");
72
73 match fork() {
74 Ok(Fork::Parent(child)) => {
75 // Wait for child to write
76 thread::sleep(Duration::from_millis(50));
77
78 // Read message from child
79 let message = fs::read_to_string(&message_file).expect("Failed to read message file");
80 assert_eq!(message.trim(), "hello from child");
81
82 waitpid(child).expect("Failed to wait for child");
83
84 // Cleanup
85 fs::remove_file(&message_file).ok();
86 }
87 Ok(Fork::Child) => {
88 // Write message
89 fs::write(&message_file, "hello from child").expect("Failed to write message");
90 exit(0);
91 }
92 Err(_) => panic!("Fork failed"),
93 }
94 }
95
96 #[test]
97 fn test_fork_multiple_children() {
98 let mut children = Vec::new();
99 // Tests creating and managing multiple child processes
100 // Expected behavior:
101 // 1. Parent creates 3 child processes sequentially
102 // 2. Each child exits with a different exit code
103 // 3. Parent tracks all child PIDs
104 // 4. Parent successfully waits for all children
105 // 5. No zombie processes remain
106
107 for i in 0..3 {
108 match fork() {
109 Ok(Fork::Parent(child)) => {
110 children.push(child);
111 }
112 Ok(Fork::Child) => {
113 // Each child exits with different code
114 exit(i);
115 }
116 Err(_) => panic!("Fork {} failed", i),
117 }
118 }
119
120 // Parent waits for all children
121 assert_eq!(children.len(), 3, "Should have 3 children");
122
123 for child in children {
124 assert!(waitpid(child).is_ok(), "Failed to wait for child {}", child);
125 }
126 }
127
128 #[test]
129 fn test_fork_child_inherits_environment() {
130 let test_dir = setup_test_dir(get_test_dir("fork_env"));
131 // Tests environment variable inheritance across fork
132 // Expected behavior:
133 // 1. Parent sets an environment variable before fork
134 // 2. Child inherits parent's environment
135 // 3. Child can read the environment variable
136 // 4. Child writes variable value to file for verification
137 // 5. Demonstrates environment inheritance
138 let env_file = test_dir.join("env.txt");
139
140 // Set a test environment variable
141 let test_var = "FORK_TEST_VAR";
142 let test_value = "test_value_12345";
143 unsafe {
144 env::set_var(test_var, test_value);
145 }
146
147 match fork() {
148 Ok(Fork::Parent(child)) => {
149 thread::sleep(Duration::from_millis(50));
150
151 let content = fs::read_to_string(&env_file).expect("Failed to read env file");
152 assert_eq!(content.trim(), test_value);
153
154 waitpid(child).expect("Failed to wait for child");
155
156 // Cleanup
157 fs::remove_file(&env_file).ok();
158 unsafe {
159 env::remove_var(test_var);
160 }
161 }
162 Ok(Fork::Child) => {
163 // Child should have inherited the environment
164 let value = env::var(test_var).expect("Environment variable not found");
165 fs::write(&env_file, value).expect("Failed to write env file");
166 exit(0);
167 }
168 Err(_) => panic!("Fork failed"),
169 }
170 }
171 // Tests that child process can execute external commands
172 // Expected behavior:
173 // 1. Child process forks successfully
174 // 2. Child executes 'echo' command
175 // 3. Command output is captured
176 // 4. Output is written to file
177 // 5. Parent verifies command executed successfully
178
179 #[test]
180 fn test_fork_child_can_execute_commands() {
181 let test_dir = get_test_dir("fork");
182 fs::create_dir_all(&test_dir).expect("Failed to create test directory");
183 let output_file = test_dir.join("command_output.txt");
184
185 match fork() {
186 Ok(Fork::Parent(child)) => {
187 thread::sleep(Duration::from_millis(100));
188
189 assert!(output_file.exists(), "Output file should exist");
190 let content = fs::read_to_string(&output_file).expect("Failed to read output");
191 assert!(!content.is_empty(), "Output should not be empty");
192
193 waitpid(child).expect("Failed to wait for child");
194
195 // Cleanup
196 fs::remove_file(&output_file).ok();
197 }
198 Ok(Fork::Child) => {
199 // Execute a command and save output
200 let output = Command::new("echo")
201 .arg("child executed command")
202 .output()
203 // Tests that parent and child have unique PIDs
204 // Expected behavior:
205 // 1. Parent records its PID before fork
206 // 2. Child records its PID after fork
207 // 3. Child PID differs from parent PID
208 // 4. fork() returns correct child PID to parent
209 // 5. PIDs match between fork return value and actual child PID
210 .expect("Failed to execute command");
211
212 fs::write(&output_file, &output.stdout).expect("Failed to write output");
213 exit(0);
214 }
215 Err(_) => panic!("Fork failed"),
216 }
217 }
218
219 #[test]
220 fn test_fork_child_has_different_pid() {
221 let test_dir = get_test_dir("fork");
222 fs::create_dir_all(&test_dir).expect("Failed to create test directory");
223 let pid_file = test_dir.join("pids.txt");
224
225 let parent_pid = unsafe { libc::getpid() };
226
227 match fork() {
228 Ok(Fork::Parent(child)) => {
229 thread::sleep(Duration::from_millis(50));
230
231 let content = fs::read_to_string(&pid_file).expect("Failed to read pid file");
232 let child_pid: i32 = content.trim().parse().expect("Failed to parse PID");
233
234 assert_ne!(
235 parent_pid, child_pid,
236 "Parent and child should have different PIDs"
237 );
238 assert_eq!(
239 child, child_pid,
240 "Child PID from fork() should match actual child PID"
241 );
242 // Tests that waitpid() properly synchronizes parent-child execution
243 // Expected behavior:
244 // 1. Parent forks and immediately checks for marker file
245 // 2. Marker file doesn't exist yet (child hasn't run)
246 // 3. Parent calls waitpid() to wait for child
247 // 4. Child creates marker file before exiting
248 // 5. After waitpid(), marker file exists (child completed)
249
250 waitpid(child).expect("Failed to wait for child");
251
252 // Cleanup
253 fs::remove_file(&pid_file).ok();
254 }
255 Ok(Fork::Child) => {
256 let child_pid = unsafe { libc::getpid() };
257 fs::write(&pid_file, format!("{}", child_pid)).expect("Failed to write PID");
258 exit(0);
259 }
260 Err(_) => panic!("Fork failed"),
261 }
262 }
263
264 #[test]
265 fn test_waitpid_waits_for_child() {
266 let test_dir = get_test_dir("fork");
267 fs::create_dir_all(&test_dir).expect("Failed to create test directory");
268 let marker_file = test_dir.join("wait_marker.txt");
269
270 match fork() {
271 Ok(Fork::Parent(child)) => {
272 // Marker should not exist yet
273 assert!(
274 !marker_file.exists(),
275 "Marker should not exist before child runs"
276 );
277
278 // Wait for child
279 waitpid(child).expect("Failed to wait for child");
280
281 // Now marker should exist
282 assert!(
283 marker_file.exists(),
284 "Marker should exist after child completes"
285 );
286
287 // Cleanup
288 fs::remove_file(&marker_file).ok();
289 }
290 Ok(Fork::Child) => {
291 // Sleep a bit to ensure parent checks first
292 thread::sleep(Duration::from_millis(50));
293
294 // Create marker
295 fs::write(&marker_file, "done").expect("Failed to write marker");
296 exit(0);
297 }
298 Err(_) => panic!("Fork failed"),
299 }
300 }