what would be the lowest-overhead way to accomlish calling sort [command] on my array?
To answer your question, the following program does the "standard" pipe
+ fork
+ dup2
+ exec
to spawn a sort
program to communicate with. Then the parent fdopens
the pipes to printf
/scanf
on them. Finally, parent waits for child program termination. The program is nowhere near perfect, for many reasons, including using assert
for cheap error handling.
#include <assert.h>
#include <math.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
void sort_them_with_sort_command(size_t arrlen, int arr[arrlen]) {
int in[2];
int err = pipe(in);
assert(err == 0);
int out[2];
err = pipe(out);
assert(err == 0);
int pid = fork();
assert(pid >= 0);
if (pid == 0) {
close(in[1]);
dup2(in[0], STDIN_FILENO);
close(out[0]);
dup2(out[1], STDOUT_FILENO);
const char *const cmd[2] = {"sort", "-n"};
execvp(cmd[0], (char *const *)cmd);
assert(0);
}
close(in[0]);
FILE *inf = fdopen(in[1], "w");
assert(inf != NULL);
close(out[1]);
FILE *outf = fdopen(out[0], "r");
assert(outf != NULL);
for (size_t i = 0; i < arrlen; ++i) {
err = fprintf(inf, "%d\n", arr[i]);
assert(err > 0);
}
fclose(inf);
close(in[1]);
for (size_t i = 0; i < arrlen; ++i) {
err = fscanf(outf, " %d", &arr[i]);
assert(err == 1);
}
fclose(outf);
close(out[0]);
waitpid(pid, 0, 0);
}
int main() {
int arraydata[10];
const size_t arraydatalen = sizeof(arraydata) / sizeof(*arraydata);
for (size_t i = 0; i < arraydatalen; i++) {
arraydata[i] = rand();
}
printf("Before sorting:\n");
for (size_t i = 0; i < arraydatalen; i++) {
printf("%d\n", arraydata[i]);
}
sort_them_with_sort_command(arraydatalen, arraydata);
printf("After sorting:\n");
for (size_t i = 0; i < arraydatalen; i++) {
printf("%d\n", arraydata[i]);
}
return 0;
}
Program outputs:
Before sorting:
1804289383
846930886
1681692777
1714636915
1957747793
424238335
719885386
1649760492
596516649
1189641421
After sorting:
424238335
596516649
719885386
846930886
1189641421
1649760492
1681692777
1714636915
1804289383
1957747793
Can I run sort with a simple one-line program using system()?
As system()
executes another process with no any means of communication, you would have to write a means of communication between processes. You could open a pipe and then write from the shell to one part of the pipe and read in a separate thread in C from the other side of the pipe. Either way, this is way overkill for sorting.