@@ -58,7 +58,7 @@ void test_poll(int *fd, int data_available) {
5858 assert (pfds [1 ].revents == POLLOUT );
5959}
6060
61- int main () {
61+ int test_most () {
6262 int fd [2 ];
6363 unsigned char wchar = 0 ;
6464 unsigned char rchar = 0 ;
@@ -154,3 +154,36 @@ int main() {
154154 puts ("success" );
155155 return 0 ;
156156}
157+
158+ int test_redirect_stderr_to_pipe () {
159+ int stderrfd = fileno (stderr );
160+ int pipefd [2 ];
161+ int original_fd = dup (stderrfd ); // duplicate stderr to original_fd, and original_fd is used to restore stderr later
162+ assert (original_fd >= 0 );
163+ assert (pipe (pipefd ) == 0 );
164+
165+ int read_end_fd = pipefd [0 ];
166+ int write_end_fd = pipefd [1 ];
167+
168+ assert (dup2 (write_end_fd , stderrfd ) == stderrfd ); // now things write to fd(stderr) is redirected to write_end_fd
169+ assert (close (write_end_fd ) == 0 ); // close the write end of the pipe after duplicating
170+
171+ assert (write (stderrfd , "xyz" , 3 ) == 3 ); // write to the stderr, expected to be read from pipe
172+
173+ assert (dup2 (original_fd , stderrfd ) == stderrfd ); // restore fd (stderr) to its original state
174+ assert (close (original_fd ) == 0 );
175+
176+ char buffer [10 ];
177+ memset (buffer , 0 , 10 );
178+ assert (read (read_end_fd , buffer , 10 ) == 3 );
179+ assert (strcmp (buffer , "xyz" ) == 0 );
180+ assert (close (read_end_fd ) == 0 ); // Close the read end of the pipe
181+ printf ("success\n" );
182+ return 0 ;
183+ }
184+
185+ int main () {
186+ test_most ();
187+ test_redirect_stderr_to_pipe ();
188+ return 0 ;
189+ }
0 commit comments