简体   繁体   中英

Can I run a program with input from the buffer?

I am looking to run a program on a target that is in memory.

For example I would like to call LaTeX on a set of characters in the memory instead of in file.

I realise I can set a file pointer in C to target memory and read/write to and from memory.

However I don't know if there is any way to pass LaTeX a file pointer or a wrapper to do so?

Running on Arch Linux , I don't care if I just get environment dependent solution for now - just need a starting point.

The easiest way is to create a file in /tmp. On most modern systems, /tmp is mounted using the "tmpfs" filesystem, which stores files in memory.

Maybe you don't want to rely on /tmp being a tmpfs. In that case, you can use memfd_create to create a file descriptor which is only stored in memory. If LaTeX needs a filename, you could make it open the file directly from your process, using /proc/<your pid>/fd/<fd number> .

A third solution is to use a pipe (which is what popen uses internally). This doesn't work if LaTeX wants to seek backwards or forwards in the file - you can't seek in a pipe. On the other hand, the pipe doesn't have to store the entire file at once.

Here's a conventional solution with popen :

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char buffer[] =
        "\\documentclass[11pt]{scrartcl}\n"
        "\\begin{document}This is the document.\n"
        "\\end{document}\n";
    FILE *fp = popen("latex", "w");
    if (!fp) perror("latex"), exit(1);
    fputs(buffer, fp);
    fclose(fp);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM