interact (stdin/out) with command line programs at runtime in C - c

I think the thing I want to do is called GUI/command line wrapping sftp(1). I need an easy way to start that program and react on its output while running. Additionally I have to be able to send input to it, full interaction is required.
I tried forkpty (emulated TTY), but there wasn't one good example findable using forkpty for that job, instead several warnings about overflows in in arguments and advisories not to use it. Another weird thing about this was the windowsize argument...
Please either give me one or many example(s) on how to call & interact with command line programs in C or another way of integrating sftp in an iPhone GUI

Rejoice! Expect was created to solve exactly your problem. It's based on Tcl, which is not so pleasant, but the tool is pleasant, it's really well designed, and there's a good book by Don Libes, who created the tool.
Expect scripts are written in Tcl, but it is totally easy to integrate a Tcl script into a C program such that other parts of the C program don't even know that Tcl is being used.

Have you used any of the popular scripting languages Ruby/Python/Perl/etc? They all have pretty full featured libraires for opening and communicating with other processes.
the subprocess module in python for example, or Popen in Ruby... there would also be lots of reference material around the web to help you out.
If a GUI was also required you could look at GTK extensions

Instead of calling sftp(1), how about using libssh? It has full sftp subsystem support.

Related

Easy way to get a File Picker on Linux

I'm trying to write a small programme that needs to load a few files chosen by the user. I thought it'd be easier to use the Linux system's default file picker rather than write my own, but I literally don't have a clue where to even start looking.
So, can anyone recommend a quick and easy way to use the system's file picker on Linux in C?
As I commented, many Linux systems (e.g. a rented VPS, a consumer router box, ...) don't have any graphical user interfaces (often above X11).
If you want a GUI toolkit in C for Linux, consider using GTK. Then look at GtkFileChooserWidget & GtkFileChooser
If you want a GUI toolkit in C++ for Linux, consider using Qt.
If you want a terminal interface, learn ncurses.
If you want a web interface, use some HTTP server library like libonion or Wt, or make a FastCGI program for your existing web server.
Perhaps coding a simple shell script might be easier. Read Advanced Bash Scripting Guide. You could also use a scripting language like Python, Ruby, Ocaml, ...
If you don't know about Linux programming, read Advanced Linux Programming first. See also intro(2) & intro(3)
... a small program that needs to load a few files chosen by the user.
Just pass them as command-line arguments. It's much easier and doesn't tie you to a given GUI toolkit.
You can easily write a shell wrapper using kdialog on KDE, or dialog if you want curses in a terminal, or ... whatever other tool for whatever other environment.

Approaches to a GUI for a Large C Program

In our Bioinformatics lab we've recently been asked to create a GUI for a program written (and optimized) in C. Any GUI we designed would need to be able to feed input to and receive output from the C program, while also being easily portable to both Windows and Mac. What are ways to go about doing this?
If your looking for a GUI toolkit that works on windows/mac in C, have you considered GTK?
Download QT or wxWidgets.
Why do the hard work when someone already has and will let you use it for free? I prefer QT myself, btw.
Edit: It does mean using C++ but it will work perfectly with C code.
Use a separate program.
It doesn't break the existing code - especially important if the code has bio knowledge that a programmer might not know/understand/test.
Gui's change often, in a couple of years you are going to be rewriting the gui for NewSuperOsToolkit(tm) but the underlying worker code won't change. We have atmospheric modelling code that I'm sure was originally written in latin.
You keep the ability to run the engine code as a batch, in parallel on MPI in the cloud, and a bunch of other ways you haven't thought of.
You could write the front end GUIs in Java, and have them feed input and receive output from your C programs. I've known a couple of groups here at work that do something similar with C# and C code (but they don't have the multi-platform restraint).
This way you don't necessarily have to create your GUIs using a C toolkit.
Depending on the nature of the program, you could create an entirely separate GUI application (in any language you prefer), and fork/execute the existing program from it, redirecting it's stdin and stdout to your GUI program. Depending on how the existing program works, this could work well, or be very cumbersome.
You could also extend the existing program with GUI code in something like GTK (which has a C API), or you could use Qt (which is C++, but there's usually no problems calling C functions from C++ if you define them as 'extern "C"').
There are a number of scripting with languages that can make this easy. I'd go for tcl/tk it works on mac pretty much out of the box, and is cross platform across pretty much any machine you can think of.
Also GTK is great and a number of scripting languages have bindings for it.
You probably don't want to write your gui in c if you don't have to. use a rapid develoment scripting language.
If you want a native GUI, then go with wxWidgets or QT. (I use wxWidgets ...)
The alternative is to have an HTML based interface using Javascript and CSS. You avoid GUI libraries altogether, you get cross-platform support and the outcome is better on some dimensions, worse on others.
If you really want a standalone user interface, you can integrate it into a binary with something like WebKit.

fork/chroot equivalent for Windows server application

I have written a small custom web server application in C running on Linux. When the application receives a request it calls fork() and handles the request in a separate process, which is chrooted into a specific directory containing the files I want to make available.
I want to port the application to Windows, but neither fork() nor chroot() are available on this platform, and there don't seem to be any direct equivalents. Can you point me to a simple (and preferably well written) example of code that will provide this functionality in Windows? My C isn't all that good, so the simpler the better.
First of all, the Windows equivalent of chroot is RUNAS which is documented here. If you need to do this from a program, then studying this C++ source code should help you understand how to use the Windows API. It is not precisely the same as chroot() but Windows folk use it to create something like a chroot jail by creating a user with extremely limited permissions and only giving that user read permission on the application folder, and write permission on one folder for data.
You probably don't want to exactly emulate fork() on Windows because it doesn't sound like you need to go that far. To understand the Windows API for creating processes and how it differs from fork(), check Mr. Peabody Explains fork(). The actual current source code for Cygwin's fork implementation shows you the current state of the art.
The Microsoft documentation for CreateProcess() and CreateThread() are the place to look for more info on the differences between them.
And finally, if you don't want to learn all the nitty-gritty platform details, just write portable programs that work on Windows and Unix, why not just use the Apache Portable Runtime library itself. Here are some docs on process creation with some sample code, in C, to create a new process.
There's no such thing as fork() on Windows. You need to call CreateProcess() - this will start a separate process (mostly equivalent to calling fork() and then immediately exec() for the spawned process) and pass the parameters to it somehow. Since you seem to have all the data to process in a dedicated directory you can make use of lpCurrentDirectory parameter of CreateProcess() - just pass the directory path you previously used with chroot() there.
The absolutely simplest way of doing it is using Cygwin, the free Unix emulation layer for Windows. Download it and install a complete development environment. (Choose in the installer.) If you are lucky, you will be able to compile your program as is, no changes at all.
Of course there are downsides and some might consider this "cheating" but you asked for the simplest solution.
Without using a compatibility framework (Interix, Cygwin, ...) you're looking at using the Windows paradigm for this sort of thing.
fork/vfork is a cheap operation on UNIXes, which is why it's used often compared to multi-threading. the Windows equivalent - CreateProcess() - is by comparison an expensive operation, and for this reason you should look at using threads instead, creating them with CreateThread(). There's a lot of example code out there for CreateThread().
In terms of chroot(), Windows doesn't have this concept. There's libraries out there that claim to emulate what you need. However it depends why you want to chroot in the first place.
Reading comments, if it's simply to stop people going up the tree with ../../../../(etc), chroot would do the job, but it's no substitue for parsing input in the first place and making sure it's sane: i.e., if too many parents are specified, lock the user into a known root directory. Apache almost certainly does this as I've never had to create a chroot() environment for Apache to work...
Using fork/chroot is simply not how things are done on Windows. If you are concerned about security in subprocesses, maybe some form of virtualization or sandboxing is what you want to use. Passing complex information to the subprocess can be done by some form of RPC-solution.
It sounds to me as if you have designed your application in the Unix way, and now you want to run in on Windows without having to change anything. In that case, you may want to consider using Cygwin, but I'm not sure if/how Cygwin emulates chroot.
Consider SUA ( aka Windows Services for Unix ). It has nearly everything you need to port applications.
man chroot(interix)

Answering a Query in C, after perfoming system call

I did an application that create a partintion and format the disk using system calls...
In the middle of the process there is a query asking to type the size of the disk... What can i do in my application in order to automaticly answer that query??
can you please help me?
This is certainly possible with, for instance libexpect but I never tried it (but Google found what seems to be a good example). On my Debian machine, man libexpect says:
libexpect - programmed dialogue library with interactive programs
This library contains functions that allow Expect to be used as a Tcl
extension or to be used directly from C or C++ (without Tcl).
Depending on your operating system (windows can do it for instance) you can have the stdin for the programmed redirected to come from an output of your program.
Maybe you can use system() do run utilities like expect to control the process
fortunately, There is nothing you can do. :)

Convert console exe to dll in C

I am interested in calling SoX, an open source console application, from another Windows GUI program (written in Delphi naturally). Instead of dealing with scraping and hiding the console window, I would like to just convert the application to a DLL that I can call from my application.
Before I start down this path I am curious how much work I should expect to be in for? Are we talking a major undertaking, or is there a straight forward solution? I know some C, but am by no means an expert.
I am not expecting SoX specific details, just EXE console application conversion to DLL in general. If someone is familiar with SoX though, even better.
For the specific topic of turning a console executable into a library by modifying the C source code, it depends on how the command-line application is factored. If it's written in such a way that I/O is funneled through a small set of functions or even better function pointers, then obviously it will be trivial.
If it's all done with printf, scanf and friends, then you'll probably be best off by finding / creating an include file that all the source files include and adding a macro that redirects printf/scanf and friends to your own functions that are written so as to be amenable to DLL implementation. Things like printf can be built from vsnprintf (use the n-version for safety), so you don't need to reimplement the whole C RTL I/O subsystem. However, there is no vsscanf, but there are third-party implementations on the web.
If the code is using fprintf, fscanf, etc. to enable indirection between files and the console, you're still out of luck. The FILE structure is opaque, and unlike Pascal text files, a portable text file driver cannot be implemented. It might still be possible if you spelunk in your specific C RTL, but you'd be better advised going down the macro route and reimplementing your own renamed FILE type.
Finally, the "popen()" approach is possible in Delphi and made somewhat easier in Delphi 2009 with the TTextReader and TTextWriter classes. Combine these with TFileStream wrapped around pipes, and specify pipes for standard input, standard output and standard error in the new process and STARTF_USESTDHANDLES, etc., and it will work. If you don't feel like writing your own, there are third-party equivalents / samples on the web for Delphi too. Here's one.
In Windows, you just call CreateProcess with the SoX command line. I don't know the Delphi bindings for Win32, but I've done this exact thing in both Win32 and C#.
And now that you know CreateProcess is what you want to call, a google search on how to do that from Delphi should give you all the code you need.
Delphi Corner Article - Using CreateProcess to Execute Programs
Calling CreateProcess() the easy way
You might not even need a DLL, you can use the popen() function to run a console application and collect any output text.
Run the process, the way Indiv advised and capture the output like how Adam has shown.
However if you still want to do the DLL conversion, this will get you started
Configure SOX for windows and compile it
Create an empty DLL project using your C++ tool
Add the SOX files to be part of the project
Add a new Function called DLLMain
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID ) {return TRUE;}
Add a .DEF file (use the project name as the file name) that lists the exports in the DLL - Add the following content to it
LIBRARY "name.DLL"
EXPORTS
CallOldMain PRIVATE
Rename the main of SOX as CallOldMain
Write a CUSTOM function to log the output / return error etc.
Find all printfs / cout in the SOX application and replace it with calls to your custom function above
Once the DLL is compiled you can now call the function CallOldMain with the same parameters main programs of C expects. You could modify this signature to return the errors / output from above.
Disclaimer: I know nothing about SoX. It might be that the code is structured to make this easy, or it might be more hard. Either way, the process is the same:
First you want to find the functions in the SoX application that you want to call. Most likely the console app has code to parse the command line and call the appropriate functions. So first off, find the functions you want to use.
Next, check out the info on exporting functions in DLLs from C at this site: Creating And Using DLLs
Then make a new makefile or visual studio project file with the target being a DLL, and add the sourcefiles from the SoX program that you have modified to be exported.
You don't mention what your toolchain is, but if you configure gcc in Windows, you can use the normal config;make;make install to just compile sox. In the process, it will create a dll file, and the console app. Or, you can just specify the make target to only make the dll. This will compile a windows native library that only depends on the MS C runtime dll, and you can use this in your own app.
You can execute a console application and capture its output using pipes. You use une side of the pipe as stdout for the CreateProcess and you read from the other side like a common file.
You can see a working example written in delphi here: http://delphi.about.com/cs/adptips2001/a/bltip0201_2.htm

Resources