xref: /haiku/src/tools/fs_shell/external_commands_unix.cpp (revision f2b4344867e97c3f4e742a1b4a15e6879644601a)
1 /*
2  * Copyright 2005-2010, Ingo Weinhold, ingo_weinhold@gmx.de.
3  * Distributed under the terms of the MIT License.
4  */
5 
6 
7 #include "external_commands.h"
8 
9 #include <errno.h>
10 #include <stdio.h>
11 #include <string.h>
12 
13 
14 static FILE*
15 get_input()
16 {
17 	static FILE* sInput = fdopen(3, "r");
18 	return sInput;
19 }
20 
21 
22 static FILE*
23 get_output()
24 {
25 	static FILE* sOutput = fdopen(4, "w");
26 	return sOutput;
27 }
28 
29 
30 bool
31 FSShell::get_external_command(char* buffer, int size)
32 {
33 	// get the input stream
34 	FILE* in = get_input();
35 	if (in == NULL) {
36 		fprintf(stderr, "Error: Failed to open command input: %s\n",
37 			strerror(errno));
38 		return false;
39 	}
40 
41 	while (true) {
42 		// read a command line
43 		if (fgets(buffer, size, in) != NULL)
44 			return true;
45 
46 		// when interrupted, try again
47 		if (errno != EINTR)
48 			return false;
49 	}
50 }
51 
52 
53 void
54 FSShell::reply_to_external_command(int result)
55 {
56 	// get the output stream
57 	FILE* out = get_output();
58 	if (out == NULL) {
59 		fprintf(stderr, "Error: Failed to open command output: %s\n",
60 			strerror(errno));
61 		return;
62 	}
63 
64 	if (fprintf(out, "%d\n", result) < 0 || fflush(out) == EOF) {
65 		fprintf(stderr, "Error: Failed to write command reply to output reply: "
66 			"%s\n", strerror(errno));
67 	}
68 }
69 
70 
71 void
72 FSShell::external_command_cleanup()
73 {
74 	// The file will be closed automatically when the team exits.
75 }
76