I am packaging a program on Windows that expects to be able to externally call OpenSSH. So, I need to package ssh.exe with it and I need to force ssh.exe to always be called with a custom command line parameter (specifically -F to specify a config file it should use). There is no way to force the calling program to do this, and there are no simple ways to do this otherwise in Windows (that I can think of anyway - symlinks or cmd scripts won't work) so I was just going to write a simple wrapper in C to do it.
This is the code I put together:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int ret;
char **newv = malloc((argc + 2) * sizeof(*newv));
memmove(newv, argv, sizeof(*newv) * argc);
newv[argc] = "-F ssh.conf";
newv[argc+1] = 0;
ret = execv("ssh.orig.exe", newv);
printf("execv failed with return value of %i", ret);
return ret;
}
I then compile this code using GCC 4.6.3 in Cygwin and it runs without error; however, there is a strange behavior with regards to input and output. When you go to type at the console (confirming the authenticity of the host and entering in a password, etc) only part of the input appears on the console. For example, if I type in the word 'yes' and press enter, only the 'e' will appear on the console and SSH will display an error about needing to type 'yes' or 'no'. Doing this from the Windows command prompt will result in your input going back to the command propmt, so when you type 'yes' and press enter, you get the ''yes' is not recognized as an internal or external command...' message as if the input were being typed at the command prompt. Eventually SSH will time out after that.
So, I'm obviously missing something here, and I'm assuming it has something to do with the way execv works (at least the POSIX Cygwin version of it).
Is there something I'm missing here or are there any alternatives? I was wondering if maybe I need to fork it and redirect the I/O to the fork (although fork() doesn't seem to work - but there are other issues there on Windows). I tried using _execv from process.h but I was having issues getting the code right for that (also could have been related to trying to use gcc).
It's also possible that there may be a non-programming way to do this that I haven't thought of, but all of the possibilities I've tried don't seem to work.
Thoughts?
I ended up finding a solution to this problem. I'm sure there were other ways to do this, but this seems to fix the issue and works well. I've replaced the execv line with the following code:
ret = spawnv(P_WAIT, "ssh.orig.exe", newv);
You have to use 'P_WAIT' otherwise the parent process completes and exits and you still have the same problem as before. This causes the parent process to wait, but still transfers input and output to the child process.
Related
My very simple C program just hangs and I don’t know why.
I am trying to make a simple executable to handle multiple monotonous actions for me every time I start a new programming session.
So I decided with something simple (below) yet every time I run it, the app just hangs, never returns. So I have to Ctrl-C out of it. I have added printf commands to see if it goes anywhere, but those never appear.
My build command returns no error messages:
gcc -o tail tail.c
Just curious what I am missing.
#include <stdio.h>
#include <unistd.h>
int main() {
chdir("\\var\\www");
return 0;
}
There are at least two problems with the source code:
It is unlikely that you have a sub-directory called \var\www in your current directory — Ubuntu uses / and not \ for path separators.
Even if there was a sub-directory with the right name, your program would change directory to it but that wouldn't affect the calling program.
You should check the return value from chdir() — at minimum:
if (chdir("/var/www") != 0)
{
perror("chdir");
exit(EXIT_FAILURE);
}
And, as Max pointed out, calling your program by the name of a well-known utility such as tail is likely to lead to confusion. Use a different name.
Incidentally, don't use test as a program name either. That, too, will lead to confusion as it is a shell built-in as well as an executable in either /bin or /usr/bin. There is also a program /bin/cd or /usr/bin/cd on your machine — it will check that it can change directory, but won't affect the current directory of your shell. You have to invoke it explicitly by the full pathname to get it to run at all because cd is another shell built-in.
Two things:
First, that's not what Linux paths look like
Second, check the return value from chdir()
ie
if (chdir("/var/www") != 0)
printf("failed to change directory");
Finally, the effect of chdir() lasts for the duration of the program. It will not change the current directory of your shell once this program finishes.
The other answers adequately cover the issues in your C code. However, the reason you are seeing it hang is because you chose the name tail for your program.
In Linux, tail is a command in /usr/bin in most setups, and if you just type tail at the command line, the shell searches the $PATH first, and runs this. Without any parameters, it waits for input on its stdin. You can end it by pressing control-d to mark the end of file.
You can bypass the $PATH lookup by typing ./tail instead.
$ tail
[system tail]
$ ./tail
[tail in your current directory]
It is a good idea to use ./ as a habit, but you can also avoid confusion by not naming your program the same as common commands. Another name to avoid is test which is a shell built-in for testing various aspects of files, but appears to do nothing as it reports results in its system return code.
Is it possible to highlight text with your cursor in any program, like you do with str+c and start a tool with the highlighted text as argument?
As far as I know, in Linux as well as in Windows, one can call a script/program with a custom shortcut. I assume str+c just does the same, calling a little program with the highlighted text as argument. How to replicate this?
For demonstration purposes, let's take this C - program printing the value it was called with:
#include <stdio.h>
int main(int argc, char**argv){
if(argc == 2){
printf("program called with: '%s'\n", argv[1]);
}
}
Can one type the text "HelloWorld" in Word for example, highlight it, and press something like str+alt+p, calling
someprogram.exe HelloWorld
or as for Linux
someprogram HelloWorld
I am really curious if this is possible.
Edit: I'm interested to know, how to replicate the clipboard.exe functionality. I have written a program "write_custom.exe" storing anything given as argument (argv[1]) in a text-file, after deleting it's previous content. Other programs can read the content of this text-file and so are able to use this custom clipboard. It's purpose is mainly for self-teaching.
As I am at the beginning of my codeing career, I only know C, but I am open for solutions in other languages as well. My goal is to run this write_custom.exe, with highlighted text as argument, on my computer and my Linux-VM.
You might want to check out ncurses (Linux) and Console API (Windows). The code will not be cross-platform, but you can pretty easily write some code to make them share some basic behavior :).
Currently I am developing a couple of C programs on my mac using Xcode. There however is 1 problem. My study requires me to use some sort of input field through the coding. So for instance if the users wants to run the program 10 times or wants the program to create 10 answers. I am using "atoi(argv[1])" just to get the input from the user.
This is exactly the problem. As soon as I run the program it just starts to bug, which is normal I quess because he is waiting for the input and not receiving it or something else. Anyways I tried to solve this problem with this link: How to run command-line application from the terminal?
This unfortunately didnt solve it either. I have already tried to re-install xcode, because just entering gcc in my terminal doesnt work either, but everytime the app store auto instals it for me.
Does anyone has a fix for my problem. I would greatly appreciate it due to the fact that next friday I have another deadline :( and I wont be getting a sufficient grade if my user input is not working.
Your help is again much appreciated!
Greetings,
Kipt Scriddy
EDIT: To clarify the problem. When running the script I want it to pop up in Terminal and wether there is an input field reguired it should ask for input. At the moment he is crashing immediatly due to the lack of input. He is not waiting for the argument to be passed from the users. He is skipping that part
HOWTO Pass command line arguments to your program from Xcode IDE
Open your project's active Scheme. Easiest way to do this is from the main menu. Select Product/Scheme/Edit Scheme...
In the schema editor, you'll see several build targets on the left side; the one you want is the "Run YourProjectName" target. Select it.
On the right side you'll see four sub-tabs, including Info, Arguments, Options, and Diagnostics. Select Arguments
Add/Remove any arguments you need. In your case, add /phi as the first argument, then 10 as the second.
Noteworthy: This is also where you can specify the current working directory of your program at launch rather than the long, temp path Xcode uses when building your binaries. To do so:
Perform steps 1-2 from above.
Select the Options sub-tab
Click the "Use custom working directory" checkbox.
Specify the full path where you want Xcode to execute your program from.
That in combination with getting your parameter handling fixed in your program should get you up and running.
Sounds to me like you want to get your arguments from the command line and if they are missing, prompt the user for them
Lets assume you want the arguments: number word number
#include <stdio.h>
#include <string.h>
int number1;
char word[128];
int number2;
int main(int argc, const char **argv)
{
if (argc == 4)
{
number1 = atoi(argv[1]);
strcpy(word, argv[2]);
number2 = atoi(argv[3]);
}
else
{
do
printf("Enter number word number: ");
while (scanf("%d %s %d", &number1, word, &number2) != 3);
}
printf("I got %d '%s' %d\n", number1, word, number2);
return 0;
}
Which gives:
$ ./test
Enter number word number: 1 andy 12
I got 1 'andy' 12
$ ./test 2 pandy 56
I got 2 'pandy' 56
Note that the error-checking is poor in this example and can be improved alot (not using atoi() is one way to start).
It sounds like you need to check argc in the program as RageD points out, otherwise when launching the program with insufficient arguments will cause problems.
gcc is the c compiler - it produces an executable. When you hit 'Run' in Xcode it compiles your program and then runs the executable file created. The executable created is named the same as your Xcode project name.
To run the program you built in Xcode from the command line:
In Xcode's project navigator find the executable in the 'Products' folder
Drag the executable file into Terminal (You will get an absolute url to the executable)
add any arguments you need to run your program
Hit enter!
The result will look something similar to the snippet below (for my 'MyCommandLineApp' project):
$ /Users/pliskin/Library/Developer/Xcode/DerivedData/MyCommandLineApp-hbpuxhguakaagvdlpdmqczucadim/Build/Products/Debug/MyCommandLineApp argument1 argument2
Is it possible to open a program using another program? For example:
I want to make a command line application in C that will prompt the user to type in the name of a program (lets say Microsoft Word.app), and that program will launch. Would I do something like this:
#include <stdio.h>
#include <time.h>
int main (int argc, const char * argv[]) {
char programName[1000];
printf("Type in the name of the program you would like to open: ");
scanf("%s", programName);
popen(programName);
}
However, popen() asks me for another char. How would I go about using popen() to open the program?
EDIT: The following code works!
#include <stdio.h>
#include <time.h>
int main (int argc, const char * argv[]) {
char programName[1000];
char app[100] = ".app";
char openApp[100] = "open /Applications/";
printf("Type in the name of the program you would like to open: ");
scanf("%s", programName);
strcat(openApp, programName);
strcat(openApp, app);
system(openApp);
}
popen lets you launch a program and get a file descriptor to its input or output, much like fopen works for files. For instance, if you wanted to read the output of your program, you'd use popen("program", "r"). On the other hand, if you want to write to its input, you would use popen("program", "w"). Mac OS X also allows for r+, which lets you read the output and write to the input but this capability isn't standard and shouldn't be relied on for cross-platform code.
If you just want to launch a program, you might as well use the system function, which does that and waits until the program exits, at which point it returns the status code. system actually invokes the shell to work, so arguments will undergo expansion (environment variables, ~, etc).
EDIT Following your comment that system("Microsoft Word.app") doesn't work as you'd expect: there are several reasons for this, actually. Starting with the message you get: this is because what you wrote is equivalent to opening a terminal window and typing Microsoft Word.app. In other words, it tries to find a program called "Microsoft", then pass it the argument "Word.app". You would need to either quote the program name or escape spaces to have the shell understand it's a whole program name and not a program name then an argument: system("Microsoft\ Word.app")
Now, this should complain saying that the shell can't find the program "Microsoft Word.app", which is already a step forward.
This is because on Mac OS, app files aren't executable files: they're folders that the Finder displays as a single file. You can verify that by ctrl+clicking (or right-clicking) an app and selecting "Show package contents" (this will open the app folder). The actual executable for Microsoft Word.app must be somewhere along the path of Microsoft Word.app/Contents/MacOS/Microsoft Word.
As you can see, this is getting kind of complex. Luckily enough, Apple provides the open executable, which can use a bunch of OS services to figure out those details. It allows to launch applications in the following fashion:
open -a Microsoft\ Word
This should launch Word. (Notice how you still need to escape the spaces.) In pure C code, that would get you something like this:
system("open -a Microsoft\\ Word");
If you choose to use Objective-C and Cocoa, however, there is a very simple way to open applications:
NSString* appName = #"Microsoft Word"; // no escape!
[[NSWorkspace sharedWorkspace] launchApplication:appName];
NSString objects can be created from C string easily enough:
NSString* appName = [[NSString alloc] initWithCString:programName encoding:NSUTF8StringEncoding];
[[NSWorkspace sharedWorkspace] launchApplication:appName];
[appName release];
It would be better to use system(3) for this purpose.
The popen(3) function establishes a pipeline that can be read or written by the caller. But GUI applications do not use standard input and standard output, they connect to the graphical interface server, sometimes called the "window server". This server is already running and already has decided what its keyboard input will be, and it is always writing its output to the video device.
To start a .app you should actually run the open(1) program, so try something like:
system("open /Applications/MacVim.app");
I'm looking to follow along with The C Programming Language (Second Addition) on a machine running Vista.
So far, I've found Dev-C++ the easiest IDE to do this in. However, I still have one problem. Whenever I run my compiled code, for example: a simple hello world program, it runs, but the console window just flickers on the screen, and I can't see the output.
How can I see an the output of my C programs using Dev-C++? I found a C++ specific solution, System("pause"), and a really ugly C solution, while looping fflush(stdout), but nothing nice and pretty.
I put a getchar() at the end of my programs as a simple "pause-method". Depending on your particular details, investigate getchar, getch, or getc
In Windows when a process terminates, the OS closes the associated window. This happens with all programs (and is generally desirable behaviour), but people never cease to be surprised when it happens to the ones they write themselves.
I am being slightly harsh perhaps; many IDE's execute the user's process in a shell as a child process, so that it does not own the window so it won't close when the process terminates. Although this would be trivial, Dev-C++ does not do that.
Be aware that when Dev-C++ was popular, this question appeard at least twice a day on Dev-C++'s own forum on Sourceforge. For that reason the forum has a "Read First" thread that provides a suggested solution amongst solutions to many other common problems. You should read it here.
Note that Dev-C++ is somewhat old and no longer actively maintained. It suffers most significantly from an almost unusable and very limited debugger integration. Traffic on the Dev-C++ forum has been dropping off since the release of VC++ 2005 Express, and is now down to a two or three posts a week rather than the 10 or so a day it had in 2005. All this suggest that you should consider an alternative tool IMO.
Use #include conio.h
Then add getch(); before return 0;
The easiest thing to do is to run your program directly instead of through the IDE. Open a command prompt (Start->Run->Cmd.exe->Enter), cd to the folder where your project is, and run the program from there. That way, when the program exits, the prompt window sticks around and you can read all of the output.
Alternatively, you can also re-direct standard output to a file, but that's probably not what you are going for here.
For Dev-C++, the bits you need to add are:-
At the Beginning
#include <stdlib.h>
And at the point you want it to stop - i.e. before at the end of the program, but before the final }
system("PAUSE");
It will then ask you to "Press any key to continue..."
Add this to your header file #include
and then in the end add this line : getch();
You can open a command prompt (Start -> Run -> cmd, use the cd command to change directories) and call your program from there, or add a getchar() call at the end of the program, which will wait until you press Enter. In Windows, you can also use system("pause"), which will display a "Press enter to continue..." (or something like that) message.
Add a line getchar(); or system("pause"); before your return 0; in main function.
It will work for you.
;
It works...
#include <iostream>
using namespace std;
int main ()
{
int x,y; // (Or whatever variable you want you can)
your required process syntax type here then;
cout << result
(or your required output result statement); use without space in getchar and other syntax.
getchar();
}
Now you can save your file with .cpp extension and use ctrl + f 9 to compile and then use ctrl + f 10 to execute the program.
It will show you the output window and it will not vanish with a second Until you click enter to close the output window.
i think you should link your project in console mode
just press Ctrl+h and in General tab select console.
When a program is not showing or displaying an output on the screen, using system("pause"); is the solution to it on a Windows profile.
The use of line system("PAUSE") will fix that problem and also include the pre processor directory #include<stdlib.h>.
Well when you are writing a c program and want the output log to stay instead of flickering away you only need to import the stdlib.h header file and type "system("PAUSE");" at the place you want the output screen to halt.Look at the example here.The following simple c program prints the product of 5 and 6 i.e 30 to the output window and halts the output window.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b,c;
a=5;b=6;
c=a*b;
printf("%d",c);
system("PAUSE");
return 0;
}
Hope this helped.