I have made a Tauri app. This app uses C in the backend. The C file contains multiple functions. Some functions use the sudo command to get data. I have started this C file in the Tauri app by writing the following function in src-tauri/srclib.rs:
#[command]
fn run_c_program() -> String {
// Use absolute path from the project root
let mut c_program_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
c_program_path.pop(); // Go up from src-tauri directory
c_program_path.pop(); // Go up from frontend directory
c_program_path.push("backend");
c_program_path.push("backend-c-file");
println!("Looking for C program at: {:?}", c_program_path);
// Execute the C program and capture output
match Command::new(&c_program_path).output() {
Ok(output) => {
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
println!("C program output: {}", stdout);
stdout
} else {
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
println!("C program error: {}", stderr);
format!("Error: {}", stderr)
}
}
Err(e) => {
let error_msg = format!("Failed to execute C program at {:?}: {}", c_program_path, e);
println!("{}", error_msg);
error_msg
}
}
}
I have console logged this data using the following function in src/App.jsx:
async function runCProgram() {
const output = await invoke("run_c_program");
setCProgramOutput(output);
console.log(cProgramOutput);
}
This correctly outputs the data.
However, because some of the functions require the sudo command, I can't view the output of any functions until I enter the sudo password. Instead, by default, I want to view the output of all non-sudo commands. If I enter the sudo password, I then want to view the output of all sudo commands
Add an argument to the main function:
int main(int argc, char *argv[]) {
Inside the main function, add an if statement checking which argument was provided:
// If no arguments are provided, show usage
if (argc == 1) {
printf("option_1\n");
printf("option_2\n");
printf("option_3\n");
printf("option_4\n");
}
// Handle specific function calls via command-line arguments
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "option_1") == 0) {
option_1_function();
}
else if (strcmp(argv[i], "option_2") == 0) {
option_2_function();
}
else if (strcmp(argv[i], "option_3") == 0) {
option_3_function();
}
else if (strcmp(argv[i], "option_4") == 0) {
option_4_function();
}
}
Inside src/App.jsx, run the C function which needs running:
const [cProgramOutput, setCProgramOutput] = useState("");
async function runCProgram() {
const output = await invoke("run_c_program", { "function": "option_2" });
setCProgramOutput(output);
console.log(cProgramOutput);
}