I have developed a mini-shell that accepts text from stdin. It works so far, but I need to make it return (in the little thing before the >)
The machine name they are logged into AND
The current working directory.
I have
#include <unistd.h>
in the code, and the current working directory was gotten using getcwd(2), which worked fine, but gethostname(2) does not seem to be working. It won’t compile using gcc on MINGW32, giving error: undefined referencew to ‘gethostname’ collect2: ld reurned 1 exit status.
Here is my code, so far.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
static int LINE_MAX = 10000;
static char *cmdLine = "Samcmd --> ";
int main( int argc, char *argv[] )
{
char cwd[LINE_MAX];
char hostName[LINE_MAX];
int looper = 1;
char *token = NULL;
char line[LINE_MAX];
char *placehold = NULL;
getcwd(cwd, LINE_MAX - 1);
gethostname(hostName, LINE_MAX - 1);
while ( looper == 1 )
{
printf( "%s | %s", hostName, cmdLine );
if( fgets( line, LINE_MAX, stdin ) != NULL )
{
token = strtok( line, ";" );
do{
if( strcmp(token, "exit\n") == 0 ) /*if an exit command is issued*/
{
looper = 0;
}
system(token);
token = strtok( NULL, ";" );
} while ( token != NULL );
}
}
return 0;
}
any critiques and comments are welcome 🙂
That works fine on my system, the hostname is printed, followed by the prompt. It doesn’t print the current working directory but that’s just because it’s not in the
printf, which would be more suitable as:On my system, that gives me:
If you’re not seeing the hostname, you need to be aware that the call can fail. You should check the return value from
gethostname(along witherrno) to see if this is the case.You may also want to clarify what you mean by “does not seem to be working”. Does it crash? Does it give you an empty string? Does it give you a non-empty string that you think is incorrect? Are you simply confused because only one string was output before the prompt (see above for a fix to this)?
This will greatly assist anyone here in helping you out.
Based on your added text:
I think you need to link against an extra library for that in MinGW. MinGW is not meant to provide all the functionality of UNIX (as, for example, CygWin tries to do). It’s more to provide the
gcctool chain to build Windows applications.You should add the
-lws2_32option to your compiler line (at the end) so that it brings in thews2_32library, which is where the code forgethostnameis located.Alternatively, the Win32 API includes
GetComputerNameExwhich I believe has no extra linking requirements, though your code will of course be non-portable at that point.In addition, under MinGW, you may find that you need to use WinSock (include
winsock2.hand callWSAStartup()before calling any network functions). It’s been a while since I attempted this under MinGw but I seem to recall that was a requirement (it may have changed).