Windbg Dump Generated programmatically can't be Debugged - windbg

I have a simple program:
int ExecuteCommand(wchar_t* commandLine)
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
BOOL bRet;
DWORD lpExitCode;
memset(&si, 0, sizeof(si));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
bRet = CreateProcess(
NULL, // pointer to name of executable module
commandLine, // pointer to command line string
NULL, // process security attributes
NULL, // thread security attributes
FALSE, // handle inheritance flag
NORMAL_PRIORITY_CLASS, // creation flags
NULL, // pointer to new environment block
NULL, // pointer to current directory name
&si, // pointer to STARTUPINFO
&pi // pointer to PROCESS_INFORMATION
);
if(bRet) WaitForSingleObject(pi.hProcess, INFINITE); // wait for process to finish
GetExitCodeProcess(pi.hProcess, &lpExitCode);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return lpExitCode;
}
void CreateCoreDump()
{
wchar_t buffer[256];
wsprintf(buffer, _T("windbg -p %d -c \".dump /mfh /u C:\\Tmp\\crashdump.dmp\""), GetCurrentProcessId());
ExecuteCommand(buffer);
}
DWORD ExceptionFilter()
{
CreateCoreDump();
return EXCEPTION_CONTINUE_SEARCH;
}
int _tmain(int argc, _TCHAR* argv[])
{
__try
{
int* p = NULL;
*p = 100;
}
__except(ExceptionFilter())
{
}
return 0;
}
It will generate a core dump when there is an exception, using function CreateCoreDump. Although the dump file could be generated successfully, it seems useless:
If I open this dump file using windbg, there is nothing in call stack!!!
But, if I debug this application directly in windbg, and set breakpoint at the line of calling CreateCoreDump, and then run windbg command:
.dump /mfh C:\Tmp\mydump.dmp
Open this dump file with WinDbg, I can see the full call stack.
Did I do something wrong, either in generating the dump file, or debugging the dump file using windbg?

When you attach the debugger after the exception happens, the debugger does not see the exception event. It creates a thread that has a breakpoint so the stack on that thread looks something like this:
0:001> kc
Call Site
ntdll!DbgBreakPoint
ntdll!DbgUiRemoteBreakin+0x38
kernel32!BaseThreadInitThunk+0xd
ntdll!RtlUserThreadStart+0x1d
If you manually set the current thread to thread 0 (use ~0s) you will see your stack
0:001> ~0s
ntdll!ZwWaitForSingleObject+0xa:
00000000`76e5135a c3 ret
0:000> kc
Call Site
ntdll!ZwWaitForSingleObject
KERNELBASE!WaitForSingleObjectEx
tmp!ExceptionFilter
tmp!main$filt$0
ntdll!__C_specific_handler
ntdll!RtlpExecuteHandlerForException
ntdll!RtlDispatchException
ntdll!KiUserExceptionDispatch
tmp!main
tmp!__mainCRTStartup
kernel32!BaseThreadInitThunk
ntdll!RtlUserThreadStart
When you start your program under the debugger two things happen, first, there is only one thread, and second the debugger knows about the exception so it will print something like this:
This dump file has an exception of interest stored in it.
The stored exception information can be accessed via .ecxr.
which tells you that you need to use the .ecxr commmand to get to the interesting thread. In this case you do not need to because the current debugger thread is already the one you want.

You have to add the exception record to the dump. For instance, I changed your sample to retrieve the exception information in the filter and pass it on the command line when generating the dump.
void CreateCoreDump(LPEXCEPTION_POINTERS p)
{
wchar_t buffer[256];
// I used the command line debugger, cdb, and added a "qd" command for it to exit after dumping.
wsprintf(buffer, _T("cdb.exe -p %d -c \".dump /mfh /u /xt 0x%x /xp 0x%p C:\\Tmp\\crashdump.dmp\";qd"), GetCurrentProcessId(), GetCurrentThreadId(), p);
ExecuteCommand(buffer);
}
DWORD ExceptionFilter(LPEXCEPTION_POINTERS p)
{
CreateCoreDump(p);
return EXCEPTION_CONTINUE_SEARCH;
}
int _tmain(int argc, _TCHAR* argv[])
{
__try
{
int* p = NULL;
*p = 100;
}
__except(ExceptionFilter(GetExceptionInformation()))
{
}
return 0;
}
Then when you open the dump in windgb, the debugger knows about the exception event. You can use .ecxr to set the current thread and stack at the exception point.
0:000> .ecxr
eax=00000000 ebx=00000000 ecx=6ec4471c edx=00000000 esi=00000001 edi=010c337c
eip=010c108b esp=0038f5e8 ebp=0038f818 iopl=0 nv up ei pl zr na pe nc
cs=0023 ss=002b ds=002b es=002b fs=0053 gs=002b efl=00010246
test!wmain+0x14:
010c108b c70064000000 mov dword ptr [eax],64h ds:002b:00000000=????????
0:000> kc
test!wmain
test!__tmainCRTStartup
kernel32!BaseThreadInitThunk
ntdll!__RtlUserThreadStart
ntdll!_RtlUserThreadStart

Related

CreateFile path not found error on a listed USB device with interface

Please help!
I'm trying to open a USB connection to an existing device with a listed active interface.
For that I need to open a file using a device id (path).
But CreateFile() fails with ERROR_PATH_NOT_FOUND (error code 3).
I got the following device ids from the Windows 10 Device Manager on my computer ...
"USB\VID_046D&PID_C534&MI_00\6&168DEF1E&0&0000"
"USB\VID_046D&PID_C534&MI_01\6&168DEF1E&0&0001"
"USB\VID_04F2&PID_B5EE&MI_00\6&237200EE&0&0000"
... and ran the following trivial program using one of them as input to CreateFile():
#include "..\..\test_wconsole\test_wconsole\_wconsole_.h"
#include "conio.h"
int APIENTRY wWinMain(_In_ HINSTANCE hi, _In_opt_ HINSTANCE hpi, _In_ LPWSTR c, _In_ int cs)
{
const WCHAR* path = L"USB\\VID_046D&PID_C534&MI_01\\6&168DEF1E&0&0001";
wcprintf("\nopening file \"%ws\" ... ", path);
HANDLE h_usbdevice = CreateFile
(
path,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING, FILE_FLAG_OVERLAPPED,
NULL
);
if (h_usbdevice != INVALID_HANDLE_VALUE) wcprintf("done\n"); else wcprintf("error %lu\n", GetLastError());
{ wcprintf("\n\tPress any key to proceed ... "); wcprintf("%i\n\n", _getch()); }
return NULL;
}
Here is a copy of the program’s console output:
opening file "USB\VID_046D&PID_C534&MI_01\6&168DEF1E&0&0001" ... error 3
Press any key to proceed ...
Running the program with Administrator privileges yields the same result. What am I doing wrong?

QProcess: not receiving finished() signal running Powershell script

I am developing a Qt application that, among other things, converts an Excel spreadsheet in a text delimited with tab file. This is done by running a Windows Powershell script.
My problem is that the finished() signal from the QProcess is never emitted, although the conversion is done successfully. And yes, I receive stateChanged() signal.
Powershell script (ps_excel.ps1)
(adapted from this question)
param ([string]$ent = $null, [string]$sal = $null)
$xlCSV = -4158 #value for tab delimited file
$Excel = New-Object -Com Excel.Application
$Excel.visible = $False
$Excel.displayalerts=$False
$b = $Excel.Workbooks.Open($ent)
$b.SaveAs($sal,$xlCSV)
$Excel.quit()
exit 0 #tested without exit, with exit and with exit 0
Qt app header
(For testing, the minimal case is a QDialog without other widgets.)
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QProcess>
#include <QDebug>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
QProcess *proces;
private:
Ui::Dialog *ui;
private slots:
void procFinish(int estat);
void procState(QProcess::ProcessState estat);
};
#endif // DIALOG_H
Qt app C++
#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
QString program = "C:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe";
QStringList params;
params << "-File" << "C:/Garsineu/ps_excel.ps1" << "-ent" << "C:/Garsineu/PROVAGALATEA.xls" << "-sal" << "C:/Garsineu/PROVAGALATEA.tab";
proces = new QProcess();
connect(proces, SIGNAL(finished(int)), this, SLOT(procFinish(int)));
connect(proces, SIGNAL(stateChanged(QProcess::ProcessState)), this, SLOT(procState(QProcess::ProcessState)));
proces->start(program, params);
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::procFinish(int estat)
{
qDebug() << "Finished";
}
void Dialog::procState(QProcess::ProcessState estat)
{
qDebug() << estat;
}
Although the conversion is successful and the states 1 (Started) and 2 (Running) are shown, the message "Finished" is never displayed.
I also tried to do it synchronously, by waitForFinished () method, which is always timed out.
Environment
Windows 7 Professional 64 bit
Powershell v1.0 x86
Qt 5.4.0 with minGW491_32
I appreciate your help. Thank you.
I found the solution. Apparently Powershell does not run in the same way from the console or when is called from another program (noninteractive). If I add at end of ps_excel.ps1 script:
Get-Process Powershell | Stop-Process
instead of
exit 0
I Stop really Powershell and get finished signal, with QProcess::ExitStatus = 0.

Attempt to embed Perl in C on Windows

I am trying to run the following example from
Deploy a Perl Application on Windows
with a simple "Hello.pl" (just prints "Hello" to STDOUT).
It fails. The .exe file is created but does not produce any output.
Probably this is my basic misunderstanding. Could you please point me in the right direction? Btw. the "lib folder containing all dependencies" in the project folder is empty since there are no modules in the "hello.pl". Is this a correct assumption?
Thank you very much!
The hello.c file:
#include <EXTERN.h>
#include <perl.h>
EXTERN_C void xs_init (pTHX);
EXTERN_C void boot_DynaLoader (pTHX_ CV* cv);
EXTERN_C void boot_Win32CORE (pTHX_ CV* cv);
EXTERN_C void
xs_init(pTHX)
{
char *file = __FILE__;
dXSUB_SYS;
/* DynaLoader is a special case */
newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
newXS("Win32CORE::bootstrap", boot_Win32CORE, file);
}
static PerlInterpreter *my_perl; /*** The Perl interpreter ***/
int main(int argc, char **argv, char **env)
{
argv[1] = "-Ilib";
argv[2] = "hello.pl";
PERL_SYS_INIT3(&argc,&argv,&env);
my_perl = perl_alloc();
perl_construct(my_perl);
PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
perl_parse(my_perl, NULL, argc, argv, (char **)NULL);
perl_run(my_perl);
perl_destruct(my_perl);
perl_free(my_perl);
PERL_SYS_TERM();
}
The perl file to build the compiler command:
#!/perl
use strict;
use warnings FATAL => qw(all);
use ExtUtils::Embed;
print "\nBuilding Hello\n";
my $gcc_cmd = join( ' ' , 'C:\Perl_516_portable\c\bin\gcc -Wall -mwindows -o K:\Scripts\Embed\Hello_3\hello K:\Scripts\Embed\Hello_3\hello.c',
&ccopts, &ldopts );
print STDOUT $gcc_cmd , "\n";
system( $gcc_cmd );
The output:
----------------------------------------------
Perl executable: C:\Perl_516_portable\perl\bin\perl.exe
Perl version : 5.16.3 / MSWin32-x86-multi-thread
C:\Perl_516_portable>perl K:\Scripts\Embed\Hello_3\building_3.pl
Building Hello
C:\Perl_516_portable\c\bin\gcc -Wall -mwindows -o K:\Scripts\Embed\Hello_3\hello K:\Scripts\Embed\Hello_3\hello.c -s -O2 -DWIN32 -DPERL_TEXTMODE_SCRIPTS -DPERL_IMPLICIT_CONTEXT -DPERL_IMPLICIT_SYS -fno-strict-aliasing -mms-bitfields -I"C:\Perl_516_portable\perl\lib\CORE" -s -L"C:\Perl_516_portable\perl\lib\CORE" -L"C:\Perl_516_portable\c\lib" C:\Perl_516_portable\perl\lib\CORE\libperl516.a C:\Perl_516_portable\c\i686-w64-mingw32\lib\libmoldname.a C:Perl_516_portable\c\i686-w64-mingw32\lib\libkernel32.a C:\Perl_516_portable\c\i686-w64-mingw32\lib\libuser32.a C:\Perl_516_portable\c\i686-w64-mingw32\lib\libgdi32.a C:\Perl_516_portable\c\i686-w64-mingw32\lib\libwinspool.a C:\Perl_516_portable\c\i686-w64-mingw32\lib\libcomdlg32.a C:\Perl_516_portable\c\i686-w64-mingw32\lib\libadvapi32.a C:\Perl_516_portable\c\i686-w64-mingw32\lib\libshell32.a C:\Perl_516_portable\c\i686-w64-mingw32\lib\libole32.a C:\Perl_516_portable\c\i686-w64-mingw32\lib\liboleaut32.a C:\Perl_516_portable\c\i686-w64-mingw32\lib\libnetapi32.a C:\Perl_516_portable\c\i686-w64-mingw32\lib\libuuid.a C:\Perl_516_portable\c\i686-w64-mingw32\lib\libws2_32.a C:Perl_516_portable\c\i686-w64-mingw32\lib\libmpr.a C:\Perl_516_portable\c\i686-w64-mingw32\lib\libwinmm.a C:\Perl_516_portable\c\i686-w64-mingw32\lib\libversion.a C:\Perl_516_portable\c\i686-w64-mingw32\lib\libodbc32.a C:\Perl_516_portable\c\i686-w64-mingw32\lib\libodbccp32.a C:\Perl_516_portable\c\i686-w64-mingw32\lib\libcomctl32.a
In file included from C:\Perl_516_portable\perl\lib\CORE/sys/socket.h:180:0,
from C:\Perl_516_portable\perl\lib\CORE/win32.h:356,
from C:\Perl_516_portable\perl\lib\CORE/win32thread.h:4,
from C:\Perl_516_portable\perl\lib\CORE/perl.h:2834,
from K:\Scripts\Embed\Hello_3\hello.c:2:
C:\Perl_516_portable\perl\lib\CORE/win32.h:361:26: warning: "/*" within comment [-Wcomment]
C:\Perl_516_portable\perl\lib\CORE/win32.h:362:33: warning: "/*" within comment [-Wcomment]
In file included from C:\Perl_516_portable\perl\lib\CORE/win32thread.h:4:0,
from C:\Perl_516_portable\perl\lib\CORE/perl.h:2834,
from K:\Scripts\Embed\Hello_3\hello.c:2:
C:\Perl_516_portable\perl\lib\CORE/win32.h:361:26: warning: "/*" within comment [-Wcomment]
C:\Perl_516_portable\perl\lib\CORE/win32.h:362:33: warning: "/*" within comment [-Wcomment]
K:\Scripts\Embed\Hello_3\hello.c: In function 'main':
K:\Scripts\Embed\Hello_3\hello.c:37:1: warning: control reaches end of non-void function [-Wreturn-type]
It will not work if you are in a different path than your script and c files. Remove the absolute paths K:\Scripts\Embed\Hello_3\
The "lib folder containing all dependencies" in the project folder is empty since there are no modules in the "hello.pl". Is this a correct assumption?
If hello.pl does not use any libs, yes.
int main(int argc, char **argv, char **env)
{
argv[1] = "-Ilib";
argv[2] = "hello.pl";
...
This will only work if argc is 2, i.e. you provided 2 args to your hello.exe.
You rather need to check argc and extend argv if < 2, and set argc to 2 if < 2.
Step into the executable with gdb and see what's going wrong. Compile with -g then.
In the long term, the established solution is to use PAR::Dist, or one of the commercial packers. Using the real compiler perlcc on Windows is a bit tricky.

llseek not behaving in kernel driver

I have been writing a lcd kernel driver for a LCD module. All was going well, I can write to the display, create a /dev/lcd node that I can write into and it will display the results on the screen. I thought using the llseek fops callback to position the cursor on the lcd would be good, this way I could use rewind fseek etc. However it is not working as I expected, below is a summary of what I am seeing:
The relevant lines of code from the driver side are:
loff_t lcd_llseek(struct file *filp, loff_t off, int whence)
{
switch (whence) {
case 0: // SEEK_SET
if (off > 4*LINE_LENGTH || off < 0) {
printk(KERN_ERR "unsupported SEEK_SET offset %llx\n", off);
return -EINVAL;
}
lcd_gotoxy(&lcd, off, 0, WHENCE_ABS);
break;
case 1: // SEEK_CUR
if (off > 4*LINE_LENGTH || off < -4*LINE_LENGTH) {
printk(KERN_ERR "unsupported SEEK_CUR offset %llx\n", off);
return -EINVAL;
}
lcd_gotoxy(&lcd, off, 0, WHENCE_REL);
break;
case 2: // SEEK_END (not supported, hence fall though)
default:
// how did we get here !
printk(KERN_ERR "unsupported seek operation\n");
return -EINVAL;
}
filp->f_pos = lcd.pos;
printk(KERN_INFO "lcd_llseek complete\n");
return lcd.pos;
}
int lcd_open(struct inode *inode, struct file *filp)
{
if (!atomic_dec_and_test(&lcd_available)) {
atomic_inc(&lcd_available);
return -EBUSY; // already open
}
return 0;
}
static struct file_operations fops = {
.owner = THIS_MODULE,
.write = lcd_write,
.llseek = lcd_llseek,
.open = lcd_open,
.release = lcd_release,
};
int lcd_init(void)
{
...
// allocate a new dev number (this can be dynamic or
// static if passed in as a module param)
if (major) {
devno = MKDEV(major, 0);
ret = register_chrdev_region(devno, 1, MODULE_NAME);
} else {
ret = alloc_chrdev_region(&devno, 0, 1, MODULE_NAME);
major = MAJOR(devno);
}
if (ret < 0) {
printk(KERN_ERR "alloc_chrdev_region failed\n");
goto fail;
}
// create a dummy class for the lcd
cl = class_create(THIS_MODULE, "lcd");
if (IS_ERR(cl)) {
printk(KERN_ERR "class_simple_create for class lcd failed\n");
goto fail1;
}
// create cdev interface
cdev_init(&cdev, &fops);
cdev.owner = THIS_MODULE;
ret = cdev_add(&cdev, devno, 1);
if (ret) {
printk(KERN_ERR "cdev_add failed\n");
goto fail2;
}
// create /sys/lcd/fplcd/dev so udev will add our device to /dev/fplcd
device = device_create(cl, NULL, devno, NULL, "lcd");
if (IS_ERR(device)) {
printk(KERN_ERR "device_create for fplcd failed\n");
goto fail3;
}
...
}
To test the lseek call I have the following unit test:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#define log(msg, ...) fprintf(stdout, __FILE__ ":%s():[%d]:" msg, __func__, __LINE__, __VA_ARGS__)
int lcd;
void test(void)
{
int k;
// a lot of hello's
log("hello world test\n",1);
if (lseek(lcd, 0, SEEK_CUR) == -1) {
log("failed to seek\n", 1);
}
}
int main(int argc, char **argv)
{
lcd = open("/dev/lcd", O_WRONLY);
if (lcd == -1) {
perror("unable to open lcd");
exit(EXIT_FAILURE);
}
test();
close(lcd);
return 0;
}
The files are cross compiled like so:
~/Workspace/ts4x00/lcd-module$ cat Makefile
obj-m += fls_lcd.o
all:
make -C $(KPATH) M=$(PWD) modules
$(CROSS_COMPILE)gcc -g -fPIC $(CFLAGS) lcd_unit_test.c -o lcd_unit_test
clean:
make -C $(KPATH) M=$(PWD) clean
rm -rf lcd_unit_test
~/Workspace/ts4x00/lcd-module$ make CFLAGS+="-march=armv4 -ffunction-sections -fdata-sections"
make -C ~/Workspace/ts4x00/linux-2.6.29 M=~/Workspace/ts4x00/lcd-module modules
make[1]: Entering directory `~/Workspace/ts4x00/linux-2.6.29'
CC [M] ~/Workspace/ts4x00/lcd-module/fls_lcd.o
~/Workspace/ts4x00/lcd-module/fls_lcd.c:443: warning: 'lcd_entry_mode' defined but not used
Building modules, stage 2.
MODPOST 1 modules
CC ~/Workspace/ts4x00/lcd-module/fls_lcd.mod.o
LD [M] ~/Workspace/ts4x00/lcd-module/fls_lcd.ko
make[1]: Leaving directory `~/Workspace/ts4x00/linux-2.6.29'
~/Workspace/ts4x00/arm-2008q3/bin/arm-none-linux-gnueabi-gcc -g -fPIC -march=armv4 -ffunction-sections -fdata-sections lcd_unit_test.c -o lcd_unit_test
This is the output of running the driver with the unit test is:
root#ts4700:~/devel# insmod ./fls_lcd.ko
root#ts4700:~/devel# ./lcd_unit_test
lcd_unit_test.c:test():[61]:hello world test
lcd_unit_test.c:test():[63]:failed to seek
root#ts4700:~/devel# dmesg
FLS LCD driver started
unsupported SEEK_SET offset bf0a573c
I cannot figure out why the parameters are being mucked up so badly on the kernel side, I tried to SEEK_CUR to position 0 and in the driver I get a SEEK_SET (no matter what I put in the unit test) and a crazy big number for off?
Does anyone know what is going on please ?
btw I am compiling for kernel 2.6.29 on a arm dev kit
OK sorry guys after trying to debug this all last night it comes down to compiling against the wrong kernel (I had KPATH left to a different config of the kernel than was on the sdcard)
sorry for wasting everyones time, but hopefully if someone is seeing what looks like a crazy stack in their kernel driver this might set them straight.
oh and thanks for all the help :)

I/O redirection in a C program

I want to implement a simple "cat file1 > file1" command in a C program. I have tried the following, but it does not work...
main () {
pid_t pid;
FILE *ip, *op;
char *args[3];
printf("Name of the executable program\n\t");
scanf("%s", &name[0]); // I entered cat here
printf("Name of the input file\n\t");
scanf("%s", &name[1]); //file1.txt
printf("Name of the output file\n\t");
scanf("%s", &name[0]); //file2.txt
pid = fork();
if(pid == -1)
perror("fork() error");
else if(pid > 0)
waitpid(-1, NULL, 0);
else if (pid == 0) {
op = fopen(name[2], "w");
close(1);
dup(op);
execlp(name[0], name[1], NULL);
}
return 0;
}// end of main()
I thought the execlp() will run cat file1.txt and its output will be redirected to file2.txt, but it's not and I don't know why. How do I do it?
scanf("%s", &name[0]); // I entered cat here
printf("Name of the input file\n\t");
scanf("%s", &name[1]); //file1.txt
printf("Name of the output file\n\t");
scanf("%s", &name[0]); //file2.txt
Clearly not a C&P of actual code - name should be args, and the last one should be "2" instead of 0.
Also, dup works on file descriptors, not FILE*, so need to look at open rather than fopen, or whatever method gets the fd from a FILE*
The first argument to execlp() is the name to be looked up; the second and following arguments are the argv list, starting with argv[0].
int execlp(const char *file, const char *arg0, ... /*, (char *)0 */);
For shell I/O redirection, it is easier to open files with open() than to use standard I/O (<stdio.h> and FILE *); you should also close the file you opened after the dup(), though it is easier to use dup2(). You need to allocate space to read the strings into; on many systems, the original code would crash because the pointers in str don't point anywhere. You should normally aim to exit with status 0 only if everything worked; otherwise, exit with a non-zero exit status.
This leads to:
#include <fcntl.h> /* open() */
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h> /* waitpid() */
#include <unistd.h> /* execlp(), fork(), dup2() */
int main(void)
{
pid_t pid;
pid_t corpse;
int status;
char name[3][50];
printf("Name of the executable program\n\t");
if (scanf("%49s", name[0]) != 1)
return(EXIT_FAILURE);
printf("Name of the input file\n\t");
if (scanf("%49s", name[1]) != 1)
return(EXIT_FAILURE);
printf("Name of the output file\n\t");
if (scanf("%49s", name[2]) != 1)
return(EXIT_FAILURE);
pid = fork();
if (pid == -1)
{
perror("fork() error");
return(EXIT_FAILURE);
}
else if (pid > 0)
corpse = waitpid(-1, &status, 0);
else
{
int fd = open(name[2], O_WRONLY|O_CREAT|O_EXCL, 0644);
if (fd < 0)
{
fprintf(stderr, "Failed to open %s for writing\n", name[2]);
return(EXIT_FAILURE);
}
dup2(fd, 1);
close(fd);
execlp(name[0], name[0], name[1], NULL);
fprintf(stderr, "Failed to exec %s\n", name[0]);
return(EXIT_FAILURE);
}
return(corpse == pid && status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
}
You have to either use fork() a process and reassign it's file descriptors to previously(manually) open()'ed file, or use system() call to make shell handle it for you.