Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing string to file in Swift 3 for Ubuntu Linux

I am currently porting my framework to server-side Swift and I stumbled upon a crash when writing a string to a file. Under macOS it is working.

The source code

#!/usr/bin/swift

import Foundation
let url = URL(string: "/tmp/foo")!
let line = "foobar"
print("writing to \(url)")
try line.write(to: url, atomically: true, encoding: String.Encoding.utf8)

causes that Segmentation Fault:

root@bd5d9b821031:/# ./test.swift 
writing to <CFURL 0x67b66e0 [0x7ff283886840]>{string = /tmp/foo, encoding = 0, base = (null)}
0  swift           0x000000000333cb08 llvm::sys::PrintStackTrace(llvm::raw_ostream&) + 40
1  swift           0x000000000333b2d6 llvm::sys::RunSignalHandlers() + 54
2  swift           0x000000000333d63a
3  libpthread.so.0 0x00007ff28921b330
4  libswiftCore.so 0x00007ff285c3f648 swift_getErrorValue + 8
5  libswiftCore.so 0x00007ff2896462d1 swift_getErrorValue + 60845201
6  swift           0x0000000000c161f4 llvm::MCJIT::runFunction(llvm::Function*, llvm::ArrayRef<llvm::GenericValue>) + 996
7  swift           0x0000000000c197af llvm::ExecutionEngine::runFunctionAsMain(llvm::Function*, std::vector<std::string, std::allocator<std::string> > const&, char const* const*) + 1215
8  swift           0x00000000007e6bff swift::RunImmediately(swift::CompilerInstance&, std::vector<std::string, std::allocator<std::string> > const&, swift::IRGenOptions&, swift::SILOptions const&) + 2367
9  swift           0x00000000007e0818
10 swift           0x00000000007dbab7 swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) + 2887
11 swift           0x00000000007a7568 main + 2872
12 libc.so.6       0x00007ff2879c4f45 __libc_start_main + 245
13 swift           0x00000000007a4f66
Stack dump:
0.  Program arguments: /usr/bin/swift -frontend -interpret ./test.swift -target x86_64-unknown-linux-gnu -disable-objc-interop -color-diagnostics -module-name test 
Segmentation fault

I also tried to wrap it in a do ... catch but the segfault still occurs. Any ideas how to fix it are deeply appreciated!

like image 541
Sebastian Avatar asked Mar 11 '23 00:03

Sebastian


1 Answers

I guess problem is in this line

let url = URL(string: "/tmp/foo")!

Try replacing it with

let url = URL(fileURLWithPath: "/tmp/foo")

This way you gonna get proper file url

like image 194
user28434'mstep Avatar answered Mar 16 '23 04:03

user28434'mstep