stdout file descriptor not set correctly - stdout

I am calling the IBM API, QzshSystem.
Its prerequisite is to ensure the File Descriptors- 0, 1 and 2 are available in process.
My code looks like this,
int fd0 = -1, fd1 = -1, fd2 = -1;
if (fcntl(0, F_GETFL) == -1)
{
fd0 = open("/dev/null", O_RDONLY);
if (fd0 == -1)
{
fprintf(stderr, "Error %d opening file /dev/null\n", errno);
}
}
if (fcntl(1, F_GETFL) == -1)
{
fd1 = open("/apifile.out", O_WRONLY|O_CREAT|O_TRUNC, S_IRWXU);
if (fd1 == -1)
{
fprintf(stderr, "Error %d opening file %s\n", errno, "/apifile.out");
}
}
if (fcntl(2, F_GETFL) == -1)
{
fd2 = open("/apifile.err", O_WRONLY|O_CREAT|O_TRUNC, S_IRWXU);
if (fd2 == -1)
{
fprintf(stderr, "Error %d opening file %s\n", errno, "/apifile.err");
}
}
Which is then followed with calling the API after some formatting of the arguments passed,
aReturn = QzshSystem(CmdStrng);
The API does not work (It should run a shell cmd), and returns the error 8; which from its documentation states that stdout file descriptor, 1, is not set correctly.
How is this possible? And am I supposed to fix the file descriptor for stdout using close() and an open?

Related

Lua yielding across C-call boundary

I'm trying to call lua_yield inside a debug hook, and get this error in my output. I'm wanting to yield after a certain number of instructions have been processed and was hoping this was the way to do it.
I'm writing this using some Python ctypes bindings.
yielding
b'test.lua:1: attempt to yield across C-call boundary'
I assumed this should work since I'm using LuaJIT and it has a fully resumable VM.
#lua_Hook
def l_dbg_count(L: lua_State_p, ar: ctypes.POINTER(lua_Debug)):
if ar.contents.event == EventCode.HookCount:
print("yielding")
lua_yield(L, 0)
#main method
def main():
...
lua_sethook(L, l_dbg_count, DebugEventMask.Count, 1)
luaL_loadfile(L, b"test.lua")
ret = lua_pcall(L, 0, 0, 0)
while True:
if ret != LuaError.Ok and ret != LuaError.Yield:
print(lua_tostring(L, -1))
break
elif ret == LuaError.Yield:
print("resuming")
ret = lua_resume(L, None, 0)
lua_close(L)
I first must push a new thread using lua_newthread, then calling luaL_loadfile and instead of lua_pcall, calling lua_resume.
I rewrote this in C to check if there was possible stack unwinding issues from Lua to Python.
void l_dbg_count(lua_State *L, lua_Debug *ar) {
if(ar->event == LUA_HOOKCOUNT) {
printf("yielding\n");
lua_yield(L, 0);
}
}
...
int main(int argc, char **argv) {
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_sethook(L, l_dbg_count, LUA_MASKCOUNT, 5);
lua_State *L_t = lua_newthread(L);
luaL_loadfile(L_t, "test.lua");
int ret = lua_resume(L_t, 0);
while(true) {
if(ret != 0 && ret != LUA_YIELD) {
fprintf(stderr, "%s", lua_tostring(L_t, -1));
break;
} else if(ret == LUA_YIELD) {
printf("resuming\n");
ret = lua_resume(L_t, 0);
} else {
break;
}
}
lua_close(L);
return EXIT_SUCCESS;
}
This however does break the coroutine library from working it seems, so currently looking into a possible fix for that.

electron.clipboard.readText() returns empty string

I try to use require('electron').clipboard.readText() and just get an empty string, although I have some text in the clipboard.
I see this in Console.app (not sure if this is related):
Failed to set up CFPasteboardRef 'Apple CFPasteboard general'. Error: <error: 0x7fffa6d6fda0> { count = 1, transaction: 0, voucher = 0x0, contents =
"XPCErrorDescription" => <string: 0x7fffa6d70048> { length = 18, contents = "Connection invalid" }
}
How can I fix this?
I think this is because the Electron app was started via execve() in a forked process (fork() +daemon()` actually).
One workaround is to execute /usr/bin/open as a wrapper, like so (pseudo code):
open -a argv[0] --args args[1...]
Or basically this code:
char** args = parse_args(cmd);
char* arg0 = find_in_path(args[0]);
pid_t pid = fork();
if (pid == 0) {
daemon(1, 0);
#ifdef __APPLE__
{
// We cannot directly use `execv` for a GUI app on MacOSX
// in a forked process
// (e.g. issues like https://stackoverflow.com/questions/53958926/).
// But using `open` will work around this.
int argc = 0;
for(; args[argc]; ++argc);
char** args_ext = malloc(sizeof(char*) * (argc + 5));
arg0 = "/usr/bin/open";
args_ext[0] = arg0;
args_ext[1] = "-a";
args_ext[2] = args[0];
args_ext[3] = "--args";
for(int i = 0; ; ++i) {
args_ext[i + 4] = args[i + 1];
if(!args[i + 1])
break;
}
args = args_ext;
}
#endif
execv(arg0, args);
exit(-1);
} else if (pid > 0) { // master
// go on ...
free(args);
} else {
// error handling...
}
(Basically via this commit.)

FFmpeg api iOS "Resource temporarily unavailable"

I've spent hours trying to fix this:
I'm trying to use the ffmpeg api on iOS. My Xcode project is building and I can call ffmpeg api functions. I am trying to write code that decodes a video (Without outputting anything for now), and I keep getting error -35: "Resource temporarily unavailable".
The input file is from the camera roll (.mov) and I'm using Mpeg-4 for decoding. All I'm currently doing is getting data from the file, parsing it and sending the parsed packets to the decoder. When I try to get frames, all I get is an error. Does anyone know what I'm doing wrong?
+(void)test: (NSString*)filename outfile:(NSString*)outfilename {
/* register all the codecs */
avcodec_register_all();
AVCodec *codec;
AVCodecParserContext *parser;
AVCodecContext *c= NULL;
int frame_count;
FILE* f;
AVFrame* frame;
AVPacket* avpkt;
avpkt = av_packet_alloc();
//av_init_packet(avpkt);
char buf[1024];
uint8_t inbuf[INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
uint8_t *data;
size_t data_size;
/* set end of buffer to 0 (this ensures that no overreading happens for damaged mpeg streams) */
memset(inbuf + INBUF_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
printf("Decode video file %s to %s\n", [filename cStringUsingEncoding:NSUTF8StringEncoding], [outfilename cStringUsingEncoding:NSUTF8StringEncoding]);
/* find the h264 video decoder */
codec = avcodec_find_decoder(AV_CODEC_ID_MPEG4);
if (!codec) {
fprintf(stderr, "Codec not found\n");
exit(1);
}
c = avcodec_alloc_context3(codec);
if (!c) {
fprintf(stderr, "Could not allocate video codec context\n");
exit(1);
}
if (codec->capabilities & AV_CODEC_CAP_TRUNCATED)
c->flags |= AV_CODEC_FLAG_TRUNCATED; // we do not send complete frames
/* For some codecs, such as msmpeg4 and mpeg4, width and height
MUST be initialized there because this information is not
available in the bitstream. */
/* open it */
if (avcodec_open2(c, codec, NULL) < 0) {
fprintf(stderr, "Could not open codec\n");
exit(1);
}
f = fopen([filename cStringUsingEncoding:NSUTF8StringEncoding], "rb");
if (!f) {
fprintf(stderr, "Could not open %s\n", [filename cStringUsingEncoding:NSUTF8StringEncoding]);
exit(1);
}
frame = av_frame_alloc();
if (!frame) {
fprintf(stderr, "Could not allocate video frame\n");
exit(1);
}
frame_count = 0;
parser = av_parser_init(codec->id);
if (!parser) {
fprintf(stderr, "parser not found\n");
exit(1);
}
while (!feof(f)) {
/* read raw data from the input file */
data_size = fread(inbuf, 1, INBUF_SIZE, f);
if (!data_size)
break;
/* use the parser to split the data into frames */
data = inbuf;
while (data_size > 0) {
int ret = av_parser_parse2(parser, c, &avpkt->data, &avpkt->size, data, data_size, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0);
if (ret < 0) {
fprintf(stderr, "Error while parsing\n");
exit(1);
}
data += ret;
data_size -= ret;
if (avpkt->size){
char buf[1024];
ret = avcodec_send_packet(c, avpkt);
if (ret < 0) {
fprintf(stderr, "Error sending a packet for decoding\n");
continue;
exit(1);
}
while (ret >= 0) {
ret = avcodec_receive_frame(c, frame);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF){
char e [1024];
av_strerror(ret, e, 1024);
fprintf(stderr, "Fail: %s !\n", e);
// ~~~~~~~~ This is where my program exits ~~~~~~~~~~~~~~~~~~~~~~~~~~~
return;
}
else if (ret < 0) {
fprintf(stderr, "Error during decoding\n");
exit(1);
}
}
}
}
}
/* some codecs, such as MPEG, transmit the I and P frame with a
latency of one frame. You must do the following to have a
chance to get the last frame of the video */
fclose(f);
avcodec_close(c);
av_free(c);
av_frame_free(&frame);
printf("\n");
}
AVERROR(EAGAIN) is not an error, it just means output is not yet available and you need to call _send_packet() a few more times before the first output will be available from _receive_frame().
The output is buffered (delayed) to allow for B-frames and frame threading.

How does my C application communicate with bluetoothctl?

In C language, I want to develop an application to run bluetoothctl, and then send command to it and receive the info, like we run bluetoothctl in console.
int main(void)
{
int fd, err = 0;
char* tty;
wait_pid = -1;
printf("BLEapp program start.......\r\n");
if (wait_pid == -1) {
printf("Start to run bluetoothctl......\r\n");
if ((pid = fork()) < 0) {
err = 1;
printf("Create new progress failed.\r\n");
}
else if (pid == 0) {
// Child progress, run as default when xid = 0x0 and mastAddr = 0x0
execl("/root/bluez-5.42/client/bluetoothctl", "bluetoothctl", NULL);
}
}
else {
printf("The child procress is still running.....\r\n");
err = 1;
}
//tty = ttyname(STDIN_FILENO);
//printf("stdin name is %s.\r\n", tty);
//fd = open(tty, O_WRONLY);
//if (fd < 0) {
// printf("Open stdin error..............\r\n");
//}
while (1) {
sleep(2);
fputs("devices\n", stdin);
//write(fd, "devices\n", 8);
}
return err;
}
I run bluetoothctl as child process, and want to send "devices\n" command to it, and read the listed devices. But it doesn't work.
Please help me to fix this problem.
Thanks.

Fail in release/Adhoc build But work in debug mode (ios)

Running a sample application in background mode(ios) using TCP sockets.It give message(a local notification ) when client send any message and wait for another message.It works fine when the application run in debugging, but crashes in release mode after 10 seconds.
used: xcode 4.2 & iPad 2 for testing..
This is the code I'm working with:
struct sockaddr_in serv_addr, cli_addr;
CFReadStreamRef hReadStream;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) printf("Sockfd Error\n");
bzero((char *) &serv_addr, sizeof(serv_addr));
portNo = 3600;//atoi(argv);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portNo);
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
printf("bind error\n");
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = 1;
while(newsockfd)
{
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr,
&clilen);
NSLog(#"newsockfd create %d\n",newsockfd);
remoteAdd = inet_ntoa(cli_addr.sin_addr);
//cout << remoteAdd << " port = " << cli_addr.sin_port << endl;
portNo = cli_addr.sin_port;
#if defined(__IPHONE_4_0) && !(TARGET_IPHONE_SIMULATOR)
NSLog(#"newsocket %d\n",newsockfd);
// Only do this if it is a SipSocket we are watching
if (newsockfd)
{
// Set it to non-blocking
//int set = 0;
//ioctl(newsockfd, FIONBIO, reinterpret_cast<int>(&set));
CFStreamCreatePairWithSocket (kCFAllocatorDefault, newsockfd,
&hReadStream, NULL);
if (CFReadStreamSetProperty(hReadStream,
kCFStreamNetworkServiceType,
kCFStreamNetworkServiceTypeVoIP) != TRUE)
{
// An error occured, delete the stream
if(hReadStream != NULL)
{
CFReadStreamClose(hReadStream);
CFRelease(hReadStream);
hReadStream = NULL;
}
//return -1;
}
else NSLog(#" >>>>>>>>>>>>>>>>>>> property set Here <<<<<<<<<<<<<<<<\n");
if (CFReadStreamOpen(hReadStream) != TRUE)
{
// An error occured, delete the stream
if(hReadStream != NULL)
{
CFReadStreamClose(hReadStream);
CFRelease(hReadStream);
hReadStream = NULL;
}
// return -1;
}
else NSLog(#"read....\n");
}
#endif
[self test];
}
Crash report in device log :
"Application 'Demo' exited abnormally with signal 9: Killed: 9" &
"unknown ReportCrash[10915] <Error>: Saved crashreport to
/var/mobile/Library/Logs/CrashReporter/servertest_2011-12-13-163920_EyeBalls-iPad.plist
using uid: 0 gid: 0, synthetic_euid: 501 egid: 0"
Trying to found the bug but it works fine in debug mode Exactly no error found in device log or debug window..Please help me :(
you can switch your compiler option to llvm gcc4.2 . I guess it issue related to clang.
hope it will work fine.

Resources